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?
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?
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); 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); Two solutions, one evolve creating new instance and one changes the instance of your array.
Filter:
idToRemove = DESIRED_ID; myArr = myArr.filter(function(item) { return item.Id != idToRemove; }); As you can see, the filter method returns new instance of the filtered array.
Second option is to find the index of the item and then remove it with splice:
idToRemove = DESIRED_ID; index = myArr.map(function(item) { return item.Id }).indexOf(idToRemove); myArr.splice(index, 1);