Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from array knowing its id [duplicate]

I have an array of objects:

var myArr; 

Let’s say that on page load it contains 10 objects with the following structure:

{   Id: …,   Name: … } 

How can I remove an object from myArr by its Id?

like image 637
user1765862 Avatar asked Dec 17 '15 14:12

user1765862


People also ask

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 duplicate objects from an array of objects?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do I remove an index from an array?

You can use the splice() method to remove the item from an array at specific index in JavaScript. The syntax for removing array elements can be given with splice(startIndex, deleteCount) .


1 Answers

Try like this

var id = 2; var list = [{   Id: 1,   Name: 'a' }, {   Id: 2,   Name: 'b' }, {   Id: 3,   Name: 'c' }]; var index = list.map(x => {   return x.Id; }).indexOf(id);  list.splice(index, 1); console.log(list); 

JSFIDDLE

Or you can utilize .filter()

Like this

var id = 2; var list = [{   Id: 1,   Name: 'a' }, {   Id: 2,   Name: 'b' }, {   Id: 3,   Name: 'c' }]; var lists = list.filter(x => {   return x.Id != id; }) console.log(lists); 

DEMO

like image 68
Anik Islam Abhi Avatar answered Sep 19 '22 15:09

Anik Islam Abhi