Home >Web Front-end >JS Tutorial >How Can I Find the Index of an Object in a JavaScript Array Based on a Property Value?

How Can I Find the Index of an Object in a JavaScript Array Based on a Property Value?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 12:56:15285browse

How Can I Find the Index of an Object in a JavaScript Array Based on a Property Value?

Finding the Index of an Object Array Element

When working with arrays of objects, finding the index of a specific element based on a given condition can be crucial. Here's a simple and direct way to accomplish this:

The built-in map method in JavaScript offers a convenient way to extract specific properties from an array of objects. By combining map with indexOf, we can efficiently search for the index of an element meeting a particular condition.

Example:

Consider the following input:

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 use the following code:

const pos = myArray.map(e => e.hello).indexOf('stevie');

This will return the index of the element in myArray that matches the given condition. In this case, the result would be 1.

The above is the detailed content of How Can I Find the Index of an Object in a JavaScript Array Based on a Property Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn