js多层对象数组 合并_JS对象数组合并去重?
时间: 2023-07-02 17:23:17 浏览: 281
JS数组扁平化、去重、排序操作实例详解
可以使用JavaScript的reduce()和concat()方法来合并多层对象数组。以下是一个示例代码,它将合并具有相同ID属性的对象,并将它们的数量相加:
```javascript
const arr1 = [{id: 1, name: 'A', count: 2}, {id: 2, name: 'B', count: 3}];
const arr2 = [{id: 1, name: 'A', count: 4}, {id: 3, name: 'C', count: 1}];
const mergedArr = [...arr1, ...arr2].reduce((acc, curr) => {
const index = acc.findIndex(item => item.id === curr.id);
if (index === -1) {
return [...acc, curr];
} else {
acc[index].count += curr.count;
return acc;
}
}, []);
console.log(mergedArr);
// Output: [{id: 1, name: 'A', count: 6}, {id: 2, name: 'B', count: 3}, {id: 3, name: 'C', count: 1}]
```
如果要合并多层对象数组,可以使用递归来处理每个子数组。以下是一个示例代码:
```javascript
const arr1 = [{id: 1, children: [{id: 2, name: 'A', count: 2}]}, {id: 3, name: 'B', count: 3}];
const arr2 = [{id: 1, children: [{id: 2, name: 'A', count: 4}]}, {id: 4, name: 'C', count: 1}];
function mergeArrays(arr1, arr2) {
const mergedArr = [...arr1, ...arr2].reduce((acc, curr) => {
const index = acc.findIndex(item => item.id === curr.id);
if (index === -1) {
return [...acc, curr];
} else if (curr.children) {
acc[index].children = mergeArrays(acc[index].children, curr.children);
return acc;
} else {
acc[index].count += curr.count;
return acc;
}
}, []);
return mergedArr;
}
const result = mergeArrays(arr1, arr2);
console.log(result);
// Output: [{id: 1, children: [{id: 2, name: 'A', count: 6}]}, {id: 3, name: 'B', count: 3}, {id: 4, name: 'C', count: 1}]
```
这个示例代码中,mergeArrays()函数使用递归来处理每个子数组,直到没有子数组为止。在每个子数组中,它再次使用reduce()方法来合并具有相同ID属性的对象。如果当前对象具有子数组,则递归处理该子数组。否则,它将增加当前对象的数量。最终,该函数将返回合并后的数组。
阅读全文