JonasT JonasT - 3 days ago 6
Javascript Question

remove specific line from json with jquery

I have this array:

var array = [{"a":"1","b":"2"},{"a":"3","b":"1"},{"a":"5","b":"4"}]


now i want to remove the line, lets say, where a=5. So afterwards the array looks like this:

var array = [{"a":"1","b":"2"},{"a":"3","b":"1"}]


How do i do this the easiest and fastest way?

Answer

You can use jQuery.map which allows you to return null for an element to be deleted.

eg:

var array = [{"a":"1","b":"2"},{"a":"3","b":"1"},{"a":"5","b":"4"}]
var newArray = $.map(array, function(e){
   return (e.a == "5") ? null : e;
});
// newArray contains [{"a":"1","b":"2"},{"a":"3","b":"1"}]

Live example (watch the console): http://jsfiddle.net/2Yz7f/

Comments