To get an index of an object from an array of objects, we can use the findIndex()
array method on the array containing the object elements in JavaScript.
TL;DR
// Array of objects
const objsArr = [
{ name: "John Doe", age: 23 },
{ name: "Roy Daniel", age: 25 },
];
// Get the index of the object in the array
const indexOfObject = objsArr.findIndex((obj) => {
// if the current object name key matches the string
// return boolean value true
if (obj.name === "Roy Daniel") {
return true;
}
// else return boolean value false
return false;
});
console.log(indexOfObject); // 1
For example let's say we have an array of objects like this,
// Array of objects
const objsArr = [
{ name: "John Doe", age: 23 },
{ name: "Roy Daniel", age: 25 },
];
Now, If we want to get the index of the object with the name
key that matches Roy Daniel
, we can use the findIndex()
method.
- the
findIndex()
requires a function as an argument. - the argument function will be passed the current array element every time an element is looped.
- Inside this function, we can check if the name matches
Roy Daniel
and return theboolean
value true if it matches and theboolean
valuefalse
if not. - the
findIndex()
method returns the index of the object in the array.
It can be done like this,
// Array of objects
const objsArr = [
{ name: "John Doe", age: 23 },
{ name: "Roy Daniel", age: 25 },
];
// Get the index of the object in the array
const indexOfObject = objsArr.findIndex((obj) => {
// if the current object name key matches the string
// return boolean value true
if (obj.name === "Roy Daniel") {
return true;
}
// else return boolean value false
return false;
});
console.log(indexOfObject); // 1
That's all 😃!
See the above code live in JSBin
Top comments (0)