我正在尝试使用扩展操作符将两个树对象合并为一个,但我没有得到正确的合并结果。如何使用扩展操作符完全合并两个树对象?
const tree1 = [{
comments: [{
text: "This a comment for case law 84",
id: "84"
}, {
text: "This a comment for case law 89",
id: "89"
}],
children: [{
comments: [{
text: "This a comment for case law 70",
id: "70"
}],
children: [{
comments: [{
text: "This a comment for case law 83",
id: "83"
}]
}]
}]
}];
const tree2 = [{
comments: [{
text: "This a comment for case law 184",
id: "184"
}],
children: [{
comments: [{
text: "This a comment for case law 170",
id: "170"
}],
children: [{
comments: [{
text: "This a comment for case law 183",
id: "183"
}]
}]
}]
}];
const mergedTrees = [{ ...tree2, ...tree1 }];
console.log("mergedTrees", mergedTrees);
问题是在合并具有相同键的属性时会被覆盖。最右边的属性具有最高的优先级。我需要什么来获得这种合并?:
{
"0": {
"comments": [
{
"text": "This a comment for case law 84",
"id": "84"
},
{
"text": "This a comment for case law 89",
"id": "89"
},
{
"text": "This a comment for case law 184",
"id": "184"
}
],
"children": [
{
"comments": [
{
"text": "This a comment for case law 70",
"id": "70"
},
{
"text": "This a comment for case law 170",
"id": "170"
}
],
"children": [
{
"comments": [
{
"text": "This a comment for case law 83",
"id": "83"
},
{
"text": "This a comment for case law 183",
"id": "183"
}
]
}
]
}
]
}
}如果不能使用扩展运算符,并且有其他方法可以实现,请让我知道。
发布于 2021-01-14 22:05:24
您可以按索引合并数组,并对嵌套子数组采用相同的方法。
const
merge = (a, b) => [a, b].reduce((r, array) => {
array.forEach(({ children, ...o }, i) => {
r[i] ??= { };
Object.entries(o).forEach(([k, v]) => (r[i][k] ??= []).push(...v));
if (children) r[i].children = merge(r[i].children || [], children);
});
return r;
}, []),
tree1 = [{ comments: [{ text: "This a comment for case law 84", id: "84" }], news: [{ text: "This news 1 ", id: "1" }], children: [{ comments: [{ text: "This a comment for case law 70", id: "70" }], news: [{ text: "This news 2 ", id: "2" }, { text: "This news 3 ", id: "3" }], children: [{ comments: [{ text: "This a comment for case law 83", id: "83" }], news: [{ text: "This news 4 ", id: "4" }] }] }] }],
tree2 = [{ comments: [{ text: "This a comment for case law 184", id: "184" }], news: [{ text: "This news 12 ", id: "12" }, { text: "This news 13 ", id: "13" }], children: [{ comments: [{ text: "This a comment for case law 170", id: "170" }], news: [{ text: "This news 22 ", id: "22" }, { text: "This news 33", id: "33" }], children: [{ comments: [{ text: "This a comment for case law 183", id: "183" }], news: [{ text: "This news 122 ", id: "122" }, { text: "This news 133 ", id: "133" }] }] }] }]
result = merge(tree1, tree2);
console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/65719929
复制相似问题