Home >Web Front-end >JS Tutorial >How to Remove Objects from a JavaScript Array Based on a Specific Property?

How to Remove Objects from a JavaScript Array Based on a Specific Property?

Susan Sarandon
Susan SarandonOriginal
2024-12-02 19:37:14639browse

How to Remove Objects from a JavaScript Array Based on a Specific Property?

Removing Array Elements by Property

In JavaScript, we often encounter scenarios where we need to remove elements from an array based on a specific object property. Consider the following example:

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

How to Remove an Object with a Specific Property?

To remove a specific object from this array based on its property, we can utilize the filter() method:

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

By using the filter() method, we can iterate through each object in the array and check if its field property does not match the specified value. If the property does not match, the object is added to the new array. In this case, we are removing the object with the money property.

Note:

It's important to note that filter() creates a new array with the filtered results. Any existing variables referencing the original array will not contain the filtered data. As such, when setting your original variable (myArray) to the new reference, proceed with caution.

The above is the detailed content of How to Remove Objects from a JavaScript Array Based on a Specific 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