Thursday, 29 March 2018

javascript - remove object from js array knowing it's Id




I have array of object inside razor view (javascript code).



var myArr;



on page load contains let's say 10 objects.



one object has following structure



 - Id  
- Name



how can I remove object from js array knowing it's Id?


Answer



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


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...