javascriptarraysobjectindexingkey

Get key of an array of objects, searching by value of object property


I have an array of objects as such

const aaa = [
  {id: 10, val: "xx"},
  {id: 27, val: "tr"},
  {id: 13, val: "ut"}
]

Now, I know how to search for an object by a value of one of the properties. For example:

const bbb = aaa.find(obj => (obj.id === 27) )

The above code, bbb would equal to {id: 27, val: "tr"}

Now, what I want is to find the index of the object with id 27. In other words, for the above bbb object, the answer should be 1 (second item in the array)

How do I search for that.

Thank you.


Solution

  • Use Array.prototype.findIndex()

    const haystack = [
      {id: 10, val: "xx"},
      {id: 27, val: "tr"},
      {id: 13, val: "ut"}
    ]
    const needleIndex = haystack.findIndex(obj => (obj.id === 27) );
    console.log({ needleIndex });