remove object from js array knowing it's Id
This question already has an answer here:
Try like this
var id=2;
var list=[
{ Id : 1,Name : 'a' },
{ Id : 2,Name : 'b' },
{ Id : 3,Name : 'c' }
];
var index=list.map(function(x){ return x.Id; }).indexOf(id);
list.splice(index,1);
JSFIDDLE
你能试一下吗
newArray = myArr
.filter(function(element) {
return element.id !== thisId;
});
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);
链接地址: http://www.djcxy.com/p/3214.html
下一篇: 从js数组中移除对象知道它是Id