我有一个对象数组,我试图通过另一个数组中的id列表删除多个元素。
说我有
transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];
ids = [12, 98];
然后我想结束
transactions = [{id:18, name:'trs18'}, {id:45, name:'trs145'}];
我正在尝试从transactions数组中删除具有在id数组中指定的id的元素。
我正在考虑创建一个执行过滤器的子数组,并用这个不包含ids数组中包含的元素的新子数组替换原始数组。
像
这样的东西var subArray = transactions.filter(trans => trans.id != ids)
transactions = subArray;
但我是箭头功能的新手,我不知道如何做到这一点。在文档中我只看到他们使用==作为比较运算符。但我正在寻找与元素列表进行比较的东西。
答案 0 :(得分:2)
您可以使用Array#filter与Array#includes一起检查ids
数组是否包含id
:
const transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];
const ids = [12, 98];
const result = transactions.filter(({ id }) => !ids.includes(id));
console.log(result);

另一个选项是从ids
数组中创建Set,并检查该集合是否have id
:
const transactions = [{id:12, name:'trs1'}, {id:18, name:'trs18'}, {id:45, name:'trs145'}, {id:98, name:'trs19'}];
const ids = [12, 98];
const idsSet = new Set([12, 98]);
const result = transactions.filter(({ id }) => !idsSet.has(id));
console.log(result);

答案 1 :(得分:1)
您可以使用Array#every
检查id
。
var transactions = [{ id: 12, name: 'trs1' }, { id: 18, name: 'trs18' }, { id: 45, name: 'trs145' }, { id: 98, name: 'trs19' }],
ids = [12, 98],
subArray = transactions.filter(trans => ids.every(id => trans.id !== id));
console.log(subArray);