Javascript 从数组中删除知道其 id 的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34336633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove object from array knowing its id
提问by user1765862
I have an array of objects:
我有一个对象数组:
var myArr;
Let's say that on page load it contains 10 objects with the following structure:
假设在页面加载时它包含 10 个具有以下结构的对象:
{
Id: …,
Name: …
}
How can I remove an object from myArrby its Id?
如何myArr通过其删除对象Id?
采纳答案by Anik Islam Abhi
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()
或者你可以使用.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);
回答by udidu
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 filtermethod returns new instance of the filtered array.
如您所见,该filter方法返回过滤数组的新实例。
Second option is to find the index of the item and then remove it with splice:
第二种选择是找到项目的索引,然后使用以下命令将其删除splice:
idToRemove = DESIRED_ID;
index = myArr.map(function(item) {
return item.Id
}).indexOf(idToRemove);
myArr.splice(index, 1);
回答by David F.
can you try
你能试一下吗
newArray = myArr
.filter(function(element) {
return element.id !== thisId;
});

