如何从对象数组中删除项目? 有一个属性数组,每个属性都需要删除与数组不重合的项目。 这是一个例子:
let selectedIsn = [10,15,20,30,40];
let arayObject = [{
isn:10,
name:"Bolt"
}, {
isn:13,
name:"marry"
},{
isn:15,
name:"a"
},{
isn:18,
name:"q"
}, {
isn:20,
name:"marrys"
},{
isn:25,
name:"aa"
},{
isn:30,
name:"qa"
}, {
isn:40,
name:"marrya"
},{
isn:55,
name:"sa"
},{
isn:68,
name:"qas"
}];
let deleteSelected = (q,selectedItems) => {
let arrayNew = q,
count=0;
for (var m = 0; m < q.length; m++) {
let index = selectedItems.indexOf(q[m]["isn"]);
if (index > -1) {
arrayNew.splice(m - count, 1);
count++;
}
}
return arrayNew;
}
deleteSelected(arayObject,selectedIsn);
不删除给定列表的所有元素。我不明白做错了什么。
答案 0 :(得分:3)
您可以使用.filter
函数从数组中获取所选项目
let deselected = arayObject.filter(function (a) {
return selectedIsn.indexOf(a.isn) < 0;
});
答案 1 :(得分:2)
只需使用像这样的过滤器
var result = arayObject.filter(item => selectedIsn.indexOf(item.isn)===-1);