Question:
Given an array of objects like:
var jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ];
How can we retrieve the third object ({a: 5, b: 6}) solely based on the value of a specific property, such as b, without using a for...in loop?
Answer:
The Array.prototype.filter() method provides an elegant solution to this problem. It allows us to filter an array based on a specified condition and return a new array containing only the matching elements.
To filter the array of objects based on the value of the b property, we can use the following code:
var result = jsObjects.filter(obj => { return obj.b === 6 })
In this code, the filter function takes an object as input and checks if its b property is equal to 6. If the condition is met, the object is included in the result array.
Output:
The result array will contain the following element:
[{a: 5, b: 6}]
This method effectively retrieves the desired object with minimal code and without the need for iterating through the array.
The above is the detailed content of How to Find a JavaScript Object in an Array by its Property Value?. For more information, please follow other related articles on the PHP Chinese website!