JavaScript 数组对象合并:根据 ID 合并相同对象
JavaScript 数组对象合并:根据 ID 合并相同对象
使用 JavaScript 的 reduce 方法,可以轻松地根据 ID 合并数组中相同对象的内容。
示例代码:
const arr = [
{ id: 1, name: 'John', age: 20 },
{ id: 2, name: 'Mary', age: 25 },
{ id: 1, name: 'David', age: 30 },
{ id: 3, name: 'Lisa', age: 35 },
{ id: 2, name: 'Sam', age: 40 }
];
const mergedArr = arr.reduce((result, current) => {
const existingObj = result.find(obj => obj.id === current.id);
if (existingObj) {
existingObj.name = existingObj.name + ', ' + current.name;
existingObj.age = Math.max(existingObj.age, current.age);
} else {
result.push(current);
}
return result;
}, []);
console.log(mergedArr);
输出结果:
[
{ id: 1, name: 'John, David', age: 30 },
{ id: 2, name: 'Mary, Sam', age: 40 },
{ id: 3, name: 'Lisa', age: 35 }
]
代码解释:
- 使用
reduce方法遍历数组,并传入一个回调函数,该函数接收两个参数:result:累积结果数组,初始值为[]current:当前遍历到的对象
- 在回调函数中,使用
find方法查找当前对象是否已经存在于result数组中。 - 如果存在,则将当前对象的
name属性追加到已存在的对象的name属性上,同时更新age属性为两者中的较大值。 - 如果不存在,则将当前对象添加到
result数组中。 - 最后返回
result数组。
总结:
通过使用 reduce 和 find 方法,我们可以轻松地根据 ID 合并数组中相同对象的内容。这种方法在处理重复数据时非常有用。
原文地址: https://www.cveoy.top/t/topic/qeKK 著作权归作者所有。请勿转载和采集!