如何找到在JavaScript中的多维对象/数组的值?
我有一个多维对象(这基本上是一个数组):
I have a multidimensional object (it's basically an array):
Object = {
1 : { name : bob , dinner : pizza },
2 : { name : john , dinner : sushi },
3 : { name : larry, dinner : hummus }
}
我希望能够搜索,其中最关键的是饭局的对象/数组,看它是否符合寿司。
I want to be able to search the object/array for where the key is "dinner", and see if it matches "sushi".
我知道jQuery有$ .inArray,但它似乎并没有对多维数组。或者,也许我错了。的indexOf似乎也只有在一个阵列级的工作。
I know jQuery has $.inArray, but it doesn't seem to work on multidimensional arrays. Or maybe I'm wrong. indexOf also seems to only work on one array level.
有没有功能的或现有的code这个?
Is there no function or existing code for this?
如果你有一个这样的对象
If you have an object like this
var people = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" }
];
忽略什么下文。使用filter$c$c>方法!
people.filter(function (person) { return person.dinner == "sushi" });
// => [{ "name": "john", "dinner": "sushi" }]
您可以搜索谁拥有晚餐的人:使用 href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map\">map$c$c>
You can search for people who have "dinner": "sushi"
using a map
people.map(function (person) {
if (person.dinner == "sushi") {
return person
} else {
return null
}
}); // => [null, { "name": "john", "dinner": "sushi" }, null]
或reduce$c$c>
people.reduce(function (sushiPeople, person) {
if (person.dinner == "sushi") {
return sushiPeople.concat(person);
} else {
return sushiPeople
}
}, []); // => [{ "name": "john", "dinner": "sushi" }]
我敢肯定你能概括这个任意键和值!
I'm sure you are able to generalize this to arbitrary keys and values!