Home > Web Front-end > JS Tutorial > How to Filter Objects in a JavaScript Array by Property Value?

How to Filter Objects in a JavaScript Array by Property Value?

Susan Sarandon
Release: 2024-10-30 10:07:02
Original
444 people have browsed it

How to Filter Objects in a JavaScript Array by Property Value?

Object Retrieval from an Array by Property in JavaScript

Finding objects in an array based on a specific property can be a common task. JavaScript provides an efficient way to accomplish this using the filter function.

Problem:

Given an array of objects with various properties, how can we locate objects with a specific property value?

Input:

Consider the following array:

<code class="javascript">const Obj = [
  { start: 0, length: 3, style: "text" },
  { start: 4, length: 2, style: "operator" },
  { start: 4, length: 3, style: "error" }
];</code>
Copy after login

Output:

We want to find objects where the "start" property equals 4.

<code class="javascript">const result = [
  { start: 4, length: 2, style: "operator" },
  { start: 4, length: 3, style: "error" }
];</code>
Copy after login

Solution:

Using the filter function, we can filter the array and return only the objects that meet the specified condition:

<code class="javascript">const result = Obj.filter(x => x.start === 4);
console.log(result);</code>
Copy after login

In this example, the filter function checks each object in the "Obj" array, returning an array with only the objects where the "start" property is equal to 4. The result is then logged to the console.

The above is the detailed content of How to Filter Objects in a JavaScript Array by 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