gpt4 book ai didi

javascript - Lodash 比较不同长度的对象数组

转载 作者:行者123 更新时间:2023-12-02 22:47:35 25 4
gpt4 key购买 nike

我正在使用 lodash 通过 differentWith (isEqual) 函数来比较两个对象数组。

这是我的两个数组:

数组1

[
{
"id":"28884",
"designation":"French fries",
"description":"French fries",
"prices":[
{
"price":0,
"vat":2821
}
]
},
{
"id":"28885",
"designation":"Potatoes",
"description":"Potatoes",
"prices":[
{
"price":0,
"vat":2821
}
]
}
]

数组2

[
{
"id":"28884",
"designation":"French fries",
"description":"French fries",
"prices":[
{
"price":0,
"vat":2821
}
]
},
{
"id":"28885",
"designation":"Potatoes",
"description":"Potatoes",
"prices":[
{
"price":0,
"vat":2821
}
]
},
{
"id":"30157",
"designation":"new item",
"description":null,
"prices":[
{
"price":500,
"vat":2821
}
]
}
]

这是我所做的,但不起作用:

const toAdd = _.differenceWith(array1, array2, _.isEqual);
const toRemove = _.differenceWith(array2, array1, _.isEqual);

如何删除元素?此外,如何使用 lodash 获取新元素、删除元素?谢谢!

最佳答案

问题是代码_.isEqual中的比较器无法比较数组中的两个对象。您可以编写一个自定义比较器。

一个更简单的普通 js 选项可能是

removedObjectsArray = array2.filter(item => !array1.map(obj => obj.id).includes(item.id));

这里对较大的数组进行过滤,以查找具有不在较小数组中的 id 的项目。

关于javascript - Lodash 比较不同长度的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58326586/

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