-4

I have an array that looks like this:

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

How do I find the index of the object with the key "-MrUUB4PcPD5G45NGb-y" for example?

D M
  • 5,769
  • 4
  • 12
  • 27
juanpa
  • 1
  • 2
  • 1
    [`Array#findIndex`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex). – D M Dec 22 '21 at 23:03

1 Answers1

0

You can use findIndex() and look at the Object.keys() for each object in the array to see if the key you want is in that keys array

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)
charlietfl
  • 170,828
  • 13
  • 121
  • 150