Home  >  Article  >  Web Front-end  >  How to Filter Objects in a JavaScript Array Based on a Specific Property Value?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 20:03:30659browse

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>

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>

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>

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>

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!

Statement:
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