次のような配列がある場合
var people = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
filter
Arrayオブジェクトのメソッドを使用できます。
people.filter(function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
新しいJavaScript実装では、関数式を使用できます。
people.filter(p => p.dinner == "sushi")
// => [{ "name": "john", "dinner": "sushi" }]
を"dinner": "sushi"
使用している人を検索できますmap
people.map(function (person) {
if (person.dinner == "sushi") {
return person
} else {
return null
}
}); // => [null, { "name": "john", "dinner": "sushi" }, null]
または reduce
people.reduce(function (sushiPeople, person) {
if (person.dinner == "sushi") {
return sushiPeople.concat(person);
} else {
return sushiPeople
}
}, []); // => [{ "name": "john", "dinner": "sushi" }]
これを任意のキーと値に一般化できると確信しています!