I have an array of objects like so:
var myArray = [ {field: 'id', operator: 'eq', value: id}, {field: 'cStatus', operator: 'eq', value: cStatus}, {field: 'money', operator: 'eq', value: money} ];
How do I remove a specific one based on its property?
e.g. How would I remove the array object with 'money' as the field property?
Use array. forEach() method to traverse every object of the array. For each object use delete obj. property to delete the certain object element from array of objects.
To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.
We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.
You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With