Home >Web Front-end >JS Tutorial >How to Find the Index of an Object in a JavaScript Array?
Finding an Object's Index in an Array
When searching an array of objects for a specific element, the indexOf method is not applicable. This article presents a direct approach to retrieve the index of an object meeting a certain condition.
Consider an array of objects like this:
var hello = { hello: 'world', foo: 'bar'}; var qaz = { hello: 'stevie', foo: 'baz'} var myArray = []; myArray.push(hello, qaz);
To find the index of the element whose hello property equals 'stevie', we can utilize the map function:
const pos = myArray.map(e => e.hello).indexOf('stevie');
The map function iterates through the array, extracting the value of the hello property for each object and creating a new array. The indexOf method can then be applied to this new array to find the index of the element with the desired value ('stevie' in this case).
This approach provides a single-line solution for finding the index of an object matching a specific condition within an array of objects.
The above is the detailed content of How to Find the Index of an Object in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!