Home > Web Front-end > JS Tutorial > body text

How to Filter Objects in a JavaScript Array Based on a Specific Property Value?

Mary-Kate Olsen
Release: 2024-11-01 20:03:30
Original
658 people have browsed it

How to Filter Objects in a JavaScript Array Based on a Specific Property Value?

Finding Objects in Arrays Using Property-Based Filtering in JavaScript

Question:

Given an array of objects, how can you find and extract objects based on a specific property and its value?

Input:

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

Output:

Find all objects with a "start" property equal to 4. The desired result:

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

Solution:

To achieve this, you can utilize the filter() function of JavaScript arrays. The filter() function takes a callback function as its argument, which is applied to each element in the array. The function returns a boolean value, indicating whether the element should be included in the new array.

In our case, we want to include all the objects that have a "start" property equal to 4. Here's how you would do it:

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

This will create a new array called result, which contains only the objects that meet the filter criteria. In this example, the result will be:

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

The above is the detailed content of How to Filter Objects in a JavaScript Array Based on a Specific 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!