合并多个对象数组并根据可选 属性 删除重复项
Merge multiple object arrays and removing duplicates based on optional property
说如果有这样的数组:
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')
可能我必须遍历每一个,但我想知道是否有更简单的替代方法。
您可以使用接受自定义比较器的 _.unionWith
而不是 _.unionBy
。比较逻辑为:
- 如果两个项目都有 ID,则按 ID 进行比较。
- 如果两个项目没有 ID,则按类型比较。
- 如果一个有 ID 而另一个没有,则认为它们是不同的。
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" }
]
const result = _.unionWith(arr1, arr2, arr3, (item1, item2) => {
const item1HasId = _.has(item1, "id");
const item2HasId = _.has(item2, "id");
if (item1HasId && item2HasId) //if both have ID...
return item1.id === item2.id; // ...compare by ID
if (!item1HasId && !item2HasId) //if neither has ID...
return item1.type === item2.type; // ...compare by type
return false; // otherwise not equal
});
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
说如果有这样的数组:
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')
可能我必须遍历每一个,但我想知道是否有更简单的替代方法。
您可以使用接受自定义比较器的 _.unionWith
而不是 _.unionBy
。比较逻辑为:
- 如果两个项目都有 ID,则按 ID 进行比较。
- 如果两个项目没有 ID,则按类型比较。
- 如果一个有 ID 而另一个没有,则认为它们是不同的。
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" }
]
const result = _.unionWith(arr1, arr2, arr3, (item1, item2) => {
const item1HasId = _.has(item1, "id");
const item2HasId = _.has(item2, "id");
if (item1HasId && item2HasId) //if both have ID...
return item1.id === item2.id; // ...compare by ID
if (!item1HasId && !item2HasId) //if neither has ID...
return item1.type === item2.type; // ...compare by type
return false; // otherwise not equal
});
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>