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

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

Susan Sarandon
Release: 2024-10-30 10:20:03
Original
726 people have browsed it

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

Finding Objects in an Array by Property in JavaScript

Given an array of objects, it is often necessary to find an object or objects that possess a specific property and value. To accomplish this in JavaScript, you can utilize the filter function of the array.

For example, 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

If you want to find the objects where the start property has a value of 4, you can use the following code:

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

The filter function takes a callback function as its argument. The callback function receives each element in the array as its input and returns a Boolean value. The element is included in the resulting array if the callback function returns true, and excluded otherwise.

In this example, the callback function checks if the start property of each element is equal to the value 4. If so, the element is included in the result array. The console output 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 by a Specific Property and 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