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
Barbara StreisandOriginal
2024-12-01 14:05:12496browse

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}
];

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';
});

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!

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