如何在 JavaScript 中的对象数组中查找值?

如何在 JavaScript 中的对象数组中查找值?

问题描述:

我有一个对象数组:

Object = {
   1 : { name : bob , dinner : pizza },
   2 : { name : john , dinner : sushi },
   3 : { name : larry, dinner : hummus }
}

我希望能够在对象/数组中搜索键为dinner"的位置,并查看它是否与sushi"匹配.

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 arrays of objects. Or maybe I'm wrong. indexOf also seems to only work on one array level.

有没有这方面的功能或现有代码?

Is there no function or existing code for this?

如果你有一个数组比如

var people = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" }
];

您可以使用 filter Array 对象的方法:

You can use the filter method of an Array object:

people.filter(function (person) { return person.dinner == "sushi" });
  // => [{ "name": "john", "dinner": "sushi" }]

在较新的 JavaScript 实现中,您可以使用函数表达式:

In newer JavaScript implementations you can use a function expression:

people.filter(p => p.dinner == "sushi")
  // => [{ "name": "john", "dinner": "sushi" }]

您可以使用 的人/map" rel="noreferrer">map


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

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!