Home > Web Front-end > JS Tutorial > How Can I Remove an Object from an Array Based on a Specific Object Property?

How Can I Remove an Object from an Array Based on a Specific Object Property?

Barbara Streisand
Release: 2024-12-01 14:05:12
Original
496 people have browsed it

How Can I Remove an Object from an Array Based on a Specific Object Property?

Targeted Removal of Array Elements Based on Object Property

Problem:

You possess an array of objects and seek a method to eliminate a particular element based on a specific property within that object.

Example:

Given an array like the one below:

var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];
Copy after login

How can you remove the object with 'money' as its 'field' property?

Solution:

To achieve this targeted removal, the following code snippet can be employed:

myArray = myArray.filter(function( obj ) {
    return obj.field !== 'money';
});
Copy after login

This code utilizes the filter method to create a new array that excludes the elements for which the specified condition is true. In this case, the condition is obj.field !== 'money', which checks if the field property is not equal to 'money'.

Caution:

It's important to note that the filter method returns a new array. If you have additional variables referencing the original array, they will not receive the filtered data, even if you update the original variable (myArray) with the new reference. Use with caution to avoid data inconsistencies.

The above is the detailed content of How Can I Remove an Object from an Array Based on a Specific Object Property?. 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