Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Objects from List where they meet a condition

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);

like image 653
Jason Avatar asked May 17 '13 15:05

Jason


2 Answers

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; })
like image 99
Bergi Avatar answered Oct 26 '22 10:10

Bergi


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/

like image 38
Andrew Whitaker Avatar answered Oct 26 '22 09:10

Andrew Whitaker