如何在JavaScript中的对象数组中查找值? [英] How to find a value in an array of objects in JavaScript?

查看:687
本文介绍了如何在JavaScript中的对象数组中查找值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组:

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 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?

推荐答案

如果您有一个数组,例如

If you have an array such as

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

您可以使用 filter 方法数组对象:

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" }]


您可以使用

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!

这篇关于如何在JavaScript中的对象数组中查找值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆