Home > Article > Web Front-end > How to Filter Objects in a JavaScript Array by Property Value?
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>
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>
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>
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!