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
Release: 2024-12-16 12:56:15
Original
278 people have browsed it

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);
Copy after login

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');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template