如何用lodash通过单个属性过滤/比较2个对象数组



我有以下对象数组?

let arr1 = [{
id: 1,
props: []
}, {
id: 2,
props: []
}, {
id: 3,
props: []
}]
let arr2 = [{
id: 1,
props: ['a', 'b']
}, {
id: 3,
props: []
}]

我需要以某种方式比较这两个数组,并返回一个新数组,该数组只包含ID不在两个原始数组中的对象。所以在上面的例子中,它应该只包含ID为2的对象,因为它只在arr1中。

我试着用

let arr3 = _.differenceWith(arr1, arr2, _.isEqual)

只要对象中的道具数组相似,并且我不更改它(我只在第二个数组中更改它(,它就可以工作。

我也试过这个:

let arr3 = _.filter(arr1, o => o.id === _.find(arr2, obj2 => o.id === obj2.id))

但这根本不起作用。

有什么想法吗?

您可以将_.differenceBy与所需密钥id进行比较。

let array1 = [{ id: 1, props: [] }, { id: 2, props: [] }, { id: 3, props: [] }],
array2 = [{ id: 1, props: ['a', 'b'] }, { id: 3, props: [] }],
difference = _.differenceBy(array1, array2, 'id');
console.log(difference);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

使用reduceObject.values将简化。

let arr1 = [
{
id: 1,
props: []
},
{
id: 2,
props: []
},
{
id: 3,
props: []
}
];
let arr2 = [
{
id: 1,
props: ["a", "b"]
},
{
id: 3,
props: []
}
];
const updated = Object.values(
[...arr1, ...arr2].reduce(
(acc, curr) =>
Object.assign(acc, { [curr.id]: curr.id in acc ? "" : { ...curr } }),
{}
)
).filter(x => x);
console.log(updated);

最新更新