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

How to Find a Specific JavaScript Object in an Array by Property Value Without a Loop?

DDD
Release: 2024-12-22 07:55:12
Original
736 people have browsed it

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

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

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

This code will output:

[{a: 5, b: 6}]
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template