Home >Web Front-end >JS Tutorial >How to Remove an Array Element Based on its Object Property in JavaScript?
Removing Array Elements Based on Object Property
In JavaScript, manipulating arrays of objects is a common scenario. Occasionally, you may need to remove specific elements from such arrays based on a particular property.
Consider the following scenario:
const myArray = [ { field: 'id', operator: 'eq', value: id }, { field: 'cStatus', operator: 'eq', value: cStatus }, { field: 'money', operator: 'eq', value: money }, ];
Objective: Remove the Array Element with 'money' as the Field Property
To achieve this, you can utilize the filter() method. This method creates a new array containing only the elements that satisfy a given condition.
myArray = myArray.filter(function(obj) { return obj.field !== 'money'; });
In this case, the filter function checks whether the field property of each object is not equal to 'money'. If it is not, the object is included in the new array.
Note:
It's important to remember that filter() creates a new array. If you refer to the original array using other variables, they will not contain the filtered data, even if you update the reference of the original variable (e.g., myArray) with the new array. Use this method with caution, especially when dealing with complex data structures.
The above is the detailed content of How to Remove an Array Element Based on its Object Property in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!