You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript合并相同键名的学生信息数据?

JavaScript合并数组中相同name的学生对象

原始数据

const StudentInfo = [
  {
    name:'Rajesh',
    courseDetails:{
      // 具体信息
    }
  },
  {
    name:'Amit',
    courseDetails:{
      // 具体信息
    }
  },
  {
    name:'Rajesh',
    Address:[
      // 具体信息
    ]
  }
];

期望结果

const mergedStudentInfo = [
  {
    name:'Rajesh',
    courseDetails:{
      // 具体信息
    },
    Address:[
      // 具体信息
    ]
  },
  {
    name:'Amit',
    courseDetails:{
      // 具体信息
    }
  }
];

实现方案

基础合并(浅层属性合并)

用Array.reduce()配合临时对象分组,再转成数组就能快速实现:

const merged = Object.values(StudentInfo.reduce((acc, curr) => {
  // 同名对象合并属性,无同名则直接存入临时容器
  acc[curr.name] = acc[curr.name] ? {...acc[curr.name], ...curr} : curr;
  return acc;
}, {}));

console.log(merged);

深层合并(嵌套对象也合并)

如果courseDetails这类嵌套对象内部有重复属性需要合并,可以写个递归的深层合并工具函数:

// 深层合并对象的工具函数
const deepMerge = (target, source) => {
  const result = {...target};
  for (const key in source) {
    // 碰到嵌套对象就递归合并,数组和基础类型直接覆盖
    if (source[key] instanceof Object && !Array.isArray(source[key])) {
      result[key] = deepMerge(result[key] || {}, source[key]);
    } else {
      result[key] = source[key];
    }
  }
  return result;
};

// 用深层合并完成分组
const mergedDeep = Object.values(StudentInfo.reduce((acc, curr) => {
  acc[curr.name] = acc[curr.name] ? deepMerge(acc[curr.name], curr) : curr;
  return acc;
}, {}));

逻辑说明

  1. reduce()遍历原始数组,用临时对象acc按name存储已合并的对象
  2. 遍历到每个学生对象时,判断临时对象里是否有同名记录:有则合并属性,无则新增
  3. 最后用Object.values()把临时对象的所有值转换为数组,得到最终合并结果

内容的提问来源于stack exchange,提问作者coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 16:42:13