This website collects cookies to deliver better user experience
How to get the index of an object from an array of objects in JavaScript?
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.
TL;DR
// Array of objectsconst objsArr =[{name:"John Doe",age:23},{name:"Roy Daniel",age:25},];// Get the index of the object in the arrayconst indexOfObject = objsArr.findIndex((obj)=>{// if the current object name key matches the string// return boolean value trueif(obj.name==="Roy Daniel"){returntrue;}// else return boolean value falsereturnfalse;});console.log(indexOfObject);// 1
For example let's say we have an array of objects like this,
// Array of objectsconst 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 the boolean value true if it matches and the boolean value false if not.
the findIndex() method returns the index of the object in the array.
It can be done like this,
// Array of objectsconst objsArr =[{name:"John Doe",age:23},{name:"Roy Daniel",age:25},];// Get the index of the object in the arrayconst indexOfObject = objsArr.findIndex((obj)=>{// if the current object name key matches the string// return boolean value trueif(obj.name==="Roy Daniel"){returntrue;}// else return boolean value falsereturnfalse;});console.log(indexOfObject);// 1