If you have an array like
var people = [ { "name": "bob", "dinner": "pizza" }, { "name": "john", "dinner": "sushi" }, { "name": "larry", "dinner": "hummus" } ];
You can use the filter method of an Array object:
people.filter(function (person) { return person.dinner == "sushi" }); // => [{ "name": "john", "dinner": "sushi" }]
In newer JavaScript implementations, you can use a function expression:
people.filter(p => p.dinner == "sushi") // => [{ "name": "john", "dinner": "sushi" }]
You can search for people with "dinner": "sushi" using map
people.map(function (person) { if (person.dinner == "sushi") { return person } else { return null } }); // => [null, { "name": "john", "dinner": "sushi" }, null]
or reduce
people.reduce(function (sushiPeople, person) { if (person.dinner == "sushi") { return sushiPeople.concat(person); } else { return sushiPeople } }, []); // => [{ "name": "john", "dinner": "sushi" }]
I am sure you can generalize this to arbitrary keys and values!
adamse Mar 03 '11 at 14:05 2011-03-03 14:05
source share