Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from array of objects

I have an array of objects:

[{"value":"14","label":"7"},{"value":"14","label":"7"},{"value":"18","label":"7"}] 

How I can delete this item {"value":"14","label":"7"} resulting in the new array:

 [{"value":"14","label":"7"},{"value":"18","label":"7"}] 

?

like image 285
Arthur Yakovlev Avatar asked May 02 '15 02:05

Arthur Yakovlev


People also ask

How do I remove a property from an array of objects?

To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.

How do you remove an object from an array of objects in C++?

In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.

How do I remove an object from an array by id?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.

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.


1 Answers

In ES6 (or using es6-shim) you can use Array.prototype.findIndex along with Array.prototype.splice:

arr.splice(arr.findIndex(matchesEl), 1);  function matchesEl(el) {     return el.value === '14' && el.label === '7'; } 

Or if a copy of the array is ok (and available since ES5), Array.prototype.filter's the way to go:

var withoutEl = arr.filter(function (el) { return !matchesEl(el); }); 
like image 71
Noah Freitas Avatar answered Oct 19 '22 23:10

Noah Freitas