Saturday, 27 August 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...