Home >Web Front-end >JS Tutorial >How to Find a Specific JavaScript Object in an Array by Property Value Without a Loop?
Finding Specific JavaScript Objects in Arrays Based on Property Values
Consider the array of objects below:
var jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ];
How can we retrieve a specific object, such as {a: 5, b: 6}, based on the value of a particular property, say "b," without resorting to a for...in loop?
Using Array.filter()
The Array.filter() method provides a convenient solution. It allows us to filter an array of objects based on a specified condition. In this case, we can filter the jsObjects array as follows:
var result = jsObjects.filter(obj => { return obj.b === 6 })
The filter() method returns a new array containing the objects that satisfy the condition. In our case, it will return an array with a single object: {a: 5, b: 6}.
Example
The code below demonstrates the use of Array.filter() to find the desired object:
const jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ] let result = jsObjects.filter(obj => { return obj.b === 6 }) console.log(result)
This code will output:
[{a: 5, b: 6}]
The above is the detailed content of How to Find a Specific JavaScript Object in an Array by Property Value Without a Loop?. For more information, please follow other related articles on the PHP Chinese website!