Let's say I have the following javascript object containing three objects:
var list = [
{ age: 5 },
{ age: 10 },
{ age: 15 }
];
Is there a way of selecting a subset of elements based on age using JavaScript and JQuery? For example:
$.select(list, element.age>=10);
Is there a way of selecting a subset of elements based on age…
Yes.
…using JavaScript…
Array filter
method:
list.filter(function(element){ return element.age >= 10; })
…and jQuery
$.grep
:
$.grep(list, function(element){ return element.age >= 10; })
First of all, that's not JSON, it's an array literal filled with object literals.
$.grep
is handy here:
var filtered = $.grep(list, function (el) {
return el.age >= 10;
});
Example: http://jsfiddle.net/ytmhR/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With