合并多个对象数组并根据可选属性删除重复项
说如果有这样的数组:
const arr1 = [
{ "id": "1", "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr2 = [
{ "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr3 = [
{ "id": "1", "type": "sales" },
{ "type": "sales" },
{ "type": "finance" }
]
如下所示,id
是可选的。我需要以这种方式合并数组,以使唯一性应基于id
(如果存在),否则将基于整个对象的其余部分。 前任。在这里合并的数组将是:
[
{ "id": "1", "type": "sales" },
{ "type": "sales" },
{ "id": "2", "type": "finance" },
{ "type": "finance" }
]
loadash具有.unionby
,但可选的唯一性不起作用。
const result = _.unionBy(arr1, arr2, arr3, 'id')
可能我必须迭代每个人,但是我想知道是否有任何更简单的选择。
Say if there are arrays like:
const arr1 = [
{ "id": "1", "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr2 = [
{ "type": "sales" },
{ "id": "2", "type": "finance" }
]
const arr3 = [
{ "id": "1", "type": "sales" },
{ "type": "sales" },
{ "type": "finance" }
]
As you can see, id
is optional. I need to merge arrays in such way that uniqueness should be based on id
if present, else entire rest of the object.
ex. here merged array would be:
[
{ "id": "1", "type": "sales" },
{ "type": "sales" },
{ "id": "2", "type": "finance" },
{ "type": "finance" }
]
loadash has .unionBy
but optional uniqueness doesn't work.
const result = _.unionBy(arr1, arr2, arr3, 'id')
Probably I have to iterate through each, but I was wondering if there is any simpler alternative for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
代替
_。unionby
您可以使用
接受自定义比较器。 The logic for comparison is:_. unionwith
Instead of
_.unionBy
you can use_.unionWith
which accepts a custom comparator. The logic for comparison is: