Home >Web Front-end >JS Tutorial >How to Remove an Object from an Array Based on a Specific Property Value?
Removing Array Elements Based on Object Properties
Data manipulation in arrays often involves filtering elements based on specific criteria. Let's explore how to remove an object from an array of objects based on a given property value.
Problem:
Consider an array of objects where each object has multiple properties. How do you remove a specific object from this array based on a particular property, e.g., "money"?
Example:
var myArray = [ {field: 'id', operator: 'eq', value: id}, {field: 'cStatus', operator: 'eq', value: cStatus}, {field: 'money', operator: 'eq', value: money} ];
Solution:
One approach to remove an object by property value is to use the filter method:
myArray = myArray.filter(function(obj) { return obj.field !== 'money'; });
This filter function takes each object in myArray as an argument and checks if its field property is not equal to 'money'. If the condition is met, the object is kept in the new array; otherwise, it is removed.
This operation creates a new array with the updated elements, and any variables referring to the original myArray will not be affected by the filter operation.
Note: It's important to use filter cautiously, as it doesn't mutate the original array. The updated array should be reassigned to the same variable to reflect the changes.
The above is the detailed content of How to Remove an Object from an Array Based on a Specific Property Value?. For more information, please follow other related articles on the PHP Chinese website!