【问题标题】:Finding a item in a javascript object based on an item's properties根据项目的属性在 javascript 对象中查找项目
【发布时间】:2018-10-11 01:39:36
【问题描述】:

假设我有一个这样的对象:

var things = { 
    "First Item": {"name": "First Item", "url":"firstitem" },
    "Second Item": {"name": "Second Item", "url":"seconditem" }
};

我希望能够检查任何对象值是否具有“firstitem”的 url 值,如果是,则检索与该项目关联的所有值(对于“name”和“url”)。怎么做一个循环来完成这个?

【问题讨论】:

  • 它是一个对象而不是一个数组

标签: javascript arrays loops object multidimensional-array


【解决方案1】:
var things = { 
    "First Item": {"name": "First Item", "url":"firstitem" },
    "Second Item": {"name": "Second Item", "url":"seconditem" }
};

Object.keys(things).
    filter(k => things[k].url === "firstitem").
    map(k => things[k])
// [ { name: 'First Item', url: 'firstitem' } ]

【讨论】:

    【解决方案2】:

    有两种方法可以循环这个。你可以使用foreach方法:

    for (var key in things) {
        things[key].url; // do thing with this
    }
    

    或者 Object.keys 方法

    Object.keys(things); // Returns an array of ["First Item", "Second Item"]
    

    我更喜欢第二种,因为对于您的用例,您可以这样做:

    Object.keys(things).find(elem => things[elem].url === "seconditem");
    

    如果找不到,这将返回undefined,或者在上述情况下,它将返回{"name": "Second Item", "url": "seconditem" }
    你也可以用 findIndex 代替 find,它会得到它在Object.keys()返回的数组中的索引

    更多详情:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-20
      相关资源
      最近更新 更多