2 回答

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; }

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));
請注意,這種方法不會改變原始數組。
添加回答
舉報