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

代码解释:

  1. 使用 reduce 方法遍历数组,并传入一个回调函数,该函数接收两个参数:
    • result:累积结果数组,初始值为 []
    • current:当前遍历到的对象
  2. 在回调函数中,使用 find 方法查找当前对象是否已经存在于 result 数组中。
  3. 如果存在,则将当前对象的 name 属性追加到已存在的对象的 name 属性上,同时更新 age 属性为两者中的较大值。
  4. 如果不存在,则将当前对象添加到 result 数组中。
  5. 最后返回 result 数组。

总结:

通过使用 reducefind 方法,我们可以轻松地根据 ID 合并数组中相同对象的内容。这种方法在处理重复数据时非常有用。

JavaScript 数组对象合并:根据 ID 合并相同对象

原文地址: https://www.cveoy.top/t/topic/qeKK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录