Thursday, March 29, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...