18
How to get the index of an object from an array of objects in JavaScript?
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.// 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.findIndex()
requires a function as an argument.Roy Daniel
and return the boolean
value true if it matches and the boolean
value false
if not.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
18