Finding a Matching Value in an Array of JavaScript Objects
JavaScript programmers often encounter the need to search an array of objects for a specific value. This article explains various methods to accomplish this task, focusing on the find(), findIndex(), filter(), and map() methods.
Example Array
Consider the following array of JavaScript objects:
myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},{'id':'67','foo':'baz'}];
Finding a Specific Object
To retrieve the object with an id of 45, use the find() method:
const matchingObject = myArray.find(x => x.id === '45');
Getting the Property Value
If you want to retrieve the foo property value for the matching object, use dot notation:
const fooValue = matchingObject.foo;
Finding the Index of an Object
To determine the index of the matching object, use the findIndex() method:
const matchingIndex = myArray.findIndex(x => x.id === '45');
Filtering Matching Objects
To create an array containing only the matching objects, use the filter() method:
const matchingObjects = myArray.filter(x => x.id === '45');
Mapping Matching Values
To extract an array of the matching foo property values, chain the filter() and map() methods:
const fooValues = myArray.filter(x => x.id === '45').map(x => x.foo);
Browser Compatibility Note
Arrow functions and some array methods, like find(), are not supported by older browsers. Consider using Babel with the appropriate polyfill for compatibility.
The above is the detailed content of How Can I Efficiently Find and Extract Data from an Array of JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!