Home > Web Front-end > JS Tutorial > How to Find a JavaScript Object in an Array by its Property Value?

How to Find a JavaScript Object in an Array by its Property Value?

Susan Sarandon
Release: 2024-12-26 02:16:09
Original
267 people have browsed it

How to Find a JavaScript Object in an Array by its Property Value?

Identify JavaScript Object in Array by Property Value

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

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

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}]
Copy after login

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!

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