有两个数组:
arr1 = [
{name: "gunner", id: 639, label: "group"},
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
]
arr2 = [
{name: "gunner", id: 639, label: "group"}
]
需要从存在于arr2中的arr1中删除所有值吗?
最终arr1
将是,因为arr2已经具有{name: "gunner", id: 639, label: "group"}
:
arr1 = [
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
]
我尝试了这个,但是没有按预期工作。
arr1 = arr1.filter(function(val) {
return arr2.indexOf(val) == -1;
});
如果属性顺序是可预测的,请首先在arr2
中设置一组字符串项,然后根据该集合中是否存在arr1
中的字符串项进行过滤:
const arr1 = [
{name: "gunner", id: 639, label: "group"},
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
];
const arr2 = [
{name: "gunner", id: 639, label: "group"}
];
const arr2Set = new Set(arr2.map(JSON.stringify));
const output = arr1.filter(obj => !arr2Set.has(JSON.stringify(obj)));
console.log(output);
如果您不希望或无法进行字符串化,则改为遍历对象的每个Object.entries
,并检查并非每个条目都与另一个数组匹配:
const arr1 = [
{name: "gunner", id: 639, label: "group"},
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
];
const arr2 = [
{name: "gunner", id: 639, label: "group"}
];
const output = arr1.filter((obj1) => {
const entries1 = Object.entries(obj1);
return arr2.every(obj2 => (
entries1.length !== Object.keys(obj2).length ||
entries1.some(([key, val]) => obj2[key] !== val)
));
});
console.log(output);
您应该比较那些对象中的ID,而不是对象引用。
const idsInArr2 = arr2.map(val => val.id);
arr1 = arr1.filter(val => idsInArr2.indexOf(val.id) === -1);