Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove array element based on object property

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?

like image 769
imperium2335 Avatar asked Mar 08 '13 06:03

imperium2335


People also ask

How do you remove an array element from an object 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.

How do you remove an element from an array based on condition?

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.

How do you remove an element from an array based on value?

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.

How do you remove an element from an array at a specific index?

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.


2 Answers

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.

like image 178
jAndy Avatar answered Oct 08 '22 21:10

jAndy


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);     } } 
like image 22
Niet the Dark Absol Avatar answered Oct 08 '22 19:10

Niet the Dark Absol