gpt4 book ai didi

javascript - JS 比较两个数组与对象并去除重复的属性名 ES6 方式

转载 作者:行者123 更新时间:2023-11-30 11:21:16 25 4
gpt4 key购买 nike

想要将两个数组与对象进行比较并通过其属性名称删除重复项,我有这两个:

arr1 = [{
item:"apple",
description: "lorem"
},{
item:"peach",
description: "impsum"
}]

arr2 = [{
item:"apple", description: "dolor"
},{
item:"grape", description: "enum"
}]

我想要这样的结果:

arr3 = [{
item:"peach", description: "impsum"
},{
item:"grape", description: "enum"
}]

我已经尝试过这种 es6 方法但没有用 arr3 = arr1.filter(val => !arr2.includes(val));

最佳答案

Array.includes 将不起作用,因为在 javascript {} !== {} 中。您将需要另一种方法,如 Array.every 来检查另一个数组中的每个对象是否具有与当前对象相同的 item 属性值。此外,您需要执行 arr1.filter(...)arr2.filter(...) 以及 concat 结果:

arr3 = [].concat(
arr1.filter(obj1 => arr2.every(obj2 => obj1.item !== obj2.item)),
arr2.filter(obj2 => arr1.every(obj1 => obj2.item !== obj1.item))
);

示例:

let arr1 = [{
item:"apple",
description: "lorem"
},{
item:"peach",
description: "impsum"
}];

let arr2 = [{
item:"apple", description: "dolor"
},{
item:"grape", description: "enum"
}];

let arr3 = [].concat(
arr1.filter(obj1 => arr2.every(obj2 => obj1.item !== obj2.item)),
arr2.filter(obj2 => arr1.every(obj1 => obj2.item !== obj1.item))
);

console.log(arr3);

关于javascript - JS 比较两个数组与对象并去除重复的属性名 ES6 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49764414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com