我正在尝试合并两个数组,这两个数组可能包含不同的键。
问题在于它没有像应该那样过滤已合并的数组。我需要保证它的值是唯一的。
这是两个数组:
const arr1 = [
{
id: "1",
title: "My Name"
},
{
id: "2",
title: "Your Name"
},
{
group: [
{
id: "4",
title: "Some Agreement"
},
{
id: "5",
title: "Some Beer"
}
]
}
];
const arr2 = [
{
id: "1",
title: "Company Name",
},
{
id: "2",
title: "A title",
},
{
id: "3",
title: "Question Group 1",
},
{
id: "4",
title: "Confidentiality Agreement",
},
{
id: "5",
title: "Some more",
},
{
id: "6",
title: "Ayo",
}
];
第一个数组有时可能会包含名为group
的键,它是与核心数组中对象({ id: string, title: string })类型相同的2个或更多项的混合。
第一个数组由第二个数组中的项目组成。
现在我需要将arr2
的所有项目发送到arr1
,而不从arr2
中删除这些项目,但我需要从该合并中排除已有的项目/ ID,这些已有项目/ ID 还必须与group
键/数组中的项目进行测试。 你懂吗?
这应该是arr1
的最终结果:
const arr1 = [
{
id: "1",
title: "My Name"
},
{
id: "2",
title: "Your Name"
},
{
group: [
{
id: "4",
title: "Some Agreement"
},
{
id: "5",
title: "Some Beer"
}
]
},
{
id: "3",
title: "Question Group 1",
},
{
id: "6",
title: "Ayo",
}
]
如您所见,新项目必须添加到数组的末尾,位置应该保持不变。
我创建了一个可重现的示例:https://codesandbox.io/s/determined-beaver-r5t6v?file=/src/App.js
相关的代码片段:
const handleClick = () => {
setMerge((qs) => {
const merged = [...qs, ...qs2];
const unique = merged.filter((v, i, a) => {
return v.id === a[i].id;
});
return unique;
});
};
我到了这一步,因为我甚至无法根据id将数组按独特的值进行过滤。
问题在于这个函数可以有不同的开发方式。我只需要在arr2中不允许重复项,包括"group"数组中的项。