2 回答
![?](http://img1.sycdn.imooc.com/5458692c00014e9b02200220-100-100.jpg)
TA贡献1803条经验 获得超6个赞
您可以减少数组并检查是否text存在相同的属性,然后检查 children 属性,否则将对象推送到实际结果集。
这种方法会改变左数组a。
const
merge = (a, b) => {
b.forEach(o => {
var item = a.find(q => o.text === q.text);
if (item) {
if (o.children) [item.children = item.children || [], o.children].reduce(merge);
} else {
a.push(o);
}
});
return a;
};
var data1 = [{ text: 'A', children: [{ text: 'B', children: [{ text: 'C', children: [{ text: 'B [43]', id: '43' }, { text: 'B [11]', id: '11' }] }] }] }, { text: 'W', children: [{ text: 'M', children: [{ text: 'K', children: [{ text: 'M [48]', id: '48' }] }] }, { text: 'T', children: [{ text: 'K', children: [{ text: 'S [78]', id: '78' }] }] }] }],
data2 = [{ text: 'A', children: [{ text: 'B', children: [{ text: 'C', children: [{ text: 'B [93]', id: '93' }, { text: 'B [11]', id: '11' }] }] }] }, { text: 'D', children: [{ text: 'M', children: [{ text: 'N', children: [{ text: 'M [66]', id: '66' }] }] }] }, { text: 'W', children: [{ text: 'M', children: [{ text: 'K', children: [{ text: 'M [58]', id: '58' }] }] }] }];
[data1, data2].reduce(merge);
console.log(data1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
![?](http://img1.sycdn.imooc.com/545867790001599f02200220-100-100.jpg)
TA贡献1793条经验 获得超6个赞
对于每个级别,您可以对公共对象进行分组(基于它们的text值),如果其中任何一个具有children属性,则递归合并它们:
const data_1 = [{ "text": "A", "children": [{ "text": "B", "children": [{ "text": "C", "children": [{ "text": "B [43]", "id": "43" }, { "text": "B [11]", "id": "11" }] }] }] }, { "text": "W", "children": [{ "text": "M", "children": [{ "text": "K", "children": [{ "text": "M [48]", "id": "48" }] }] }, { "text": "T", "children": [{ "text": "K", "children": [{ "text": "S [78]", "id": "78" }] }] }] }];
const data_2 = [{ "text": "A", "children": [{ "text": "B", "children": [{ "text": "C", "children": [{ "text": "B [93]", "id": "93" }, { "text": "B [11]", "id": "11" }] }] }] }, { "text": "D", "children": [{ "text": "M", "children": [{ "text": "N", "children": [{ "text": "M [66]", "id": "66" }] }] }] }, { "text": "W", "children": [{ "text": "M", "children": [{ "text": "K", "children": [{ "text": "M [58]", "id": "58" }] }] }] }];
function mergeArrays(arr1 = [], arr2 = []) {
const pairs = [...arr1, ...arr2].reduce((acc, curr) => {
acc[curr.text] = acc[curr.text] || [];
acc[curr.text].push(curr);
return acc;
}, {});
return Object.values(pairs).map(([p1, p2 = {}]) => {
const res = { ...p1, ...p2 };
if (p1.children || p2.children) res.children = mergeArrays(p1.children, p2.children);
return res;
});
}
console.log(mergeArrays(data_1, data_2));
请注意,这种方法不会改变原始数组。
添加回答
举报