【问题标题】:Find index of an object in an arrray of objects [duplicate]在对象数组中查找对象的索引[重复]
【发布时间】:2022-01-24 02:07:08
【问题描述】:

我有一个如下所示的数组:

const arr = [ 
    { "-MrUU6N2pi7aCwJoqCzP": { "name": "test", "brand": "test", "id": 1 } }, 
    { "-MrUUB4PcPD5G45NGb-y": { "name": "test2", "brand": "test2", "id": 2 } } 
]

例如,如何找到带有“-MrUUB4PcPD5G45NGb-y”键的对象的索引?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

您可以使用findIndex() 并查看数组中每个对象的Object.keys(),以查看您想要的键是否在该键数组中

const arr = [ 
  {"-MrUU6N2pi7aCwJoqCzP":{"name":"test","brand":"test","id":1}}, 
  {"-MrUUB4PcPD5G45NGb-y":{"name":"test2","brand":"test2","id":2}} 
],

keyWanted = "-MrUUB4PcPD5G45NGb-y",

idx = arr.findIndex(e => Object.keys(e).includes(keyWanted))

console.log('Index =', idx)

【讨论】:

  • 非常感谢;)
猜你喜欢
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
相关资源
最近更新 更多