Remove array element based on object property
Say you want to remove the second object by it's field property.
With ES6 it's as easy as this.
myArray.splice(myArray.findIndex(item => item.field === "cStatus"), 1)
In ES6, just one line.
const arr = arr.filter(item => item.key !== "some value");
:)
Iterate through the array, and splice
out the ones you don't want. For easier use, iterate backwards so you don't have to take into account the live nature of the array:
for (var i = myArray.length - 1; i >= 0; --i) {
if (myArray[i].field == "money") {
myArray.splice(i,1);
}
}
One possibility:
myArray = myArray.filter(function( obj ) {
return obj.field !== 'money';
});
Please note that filter
creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray
with the new reference. Use with caution.