JavaScript按id合并数组重复对象 保留字段结构适配payroll系统CSV导出
JS同ID数组对象合并(保留字段顺序+空值不覆盖非空)
实现思路
- 用
Map结构做id去重的映射表,天然保留插入顺序,保证最终数组顺序和原数组首次出现id的顺序一致 - 合并时仅当已有对象的对应字段值为空时,才用新对象的字段值覆盖,避免空值抹除已有有效数据
- 直接基于首个出现的同id对象修改,完全保留原始字段顺序,适配后续CSV导出要求
实现代码
function mergeDuplicateEmployees(arr) { const idMap = new Map(); for (const item of arr) { if (!idMap.has(item.id)) { // 首次出现的id,完整存入保留所有字段和顺序 idMap.set(item.id, { ...item }); continue; } const existing = idMap.get(item.id); // 遍历当前对象所有字段,仅空值才覆盖 for (const key in item) { if (existing[key] === '' || existing[key] == null) { existing[key] = item[key]; } } } // 转数组保留插入顺序 return Array.from(idMap.values()); } // 调用示例 const originalArr = [ { id: 'MARS03', name: 'Employee 3', T1: 9.23, A6: '', SAT: '', SUN: '', PHW: '', SAN: '', COMM:'', BON: '', other: '', quantity: '', leaveDays: '', from: '', to: '', reason: '', costCentre: '', message: '' }, { id: 'THOM01', name: 'Employee 4', T1: '', A6: '', SAT: 4.12, SUN: '', PHW: '', SAN: '', COMM: '', BON: '', other: '', quantity: '', leaveDays: '', from: '', to: '', reason: '', costCentre: '', message: '' }, { id: 'THOM01', name: 'Employee 4', T1: '', A6: '', SAT: '', SUN: 6.12, PHW: '', SAN: '', COMM: '', BON: '', other: '', quantity: '', leaveDays: '', from: '', to: '', reason: '', costCentre: '', message: '' }, { id: 'THOM01', name: 'Employee 4', T1: 15, A6: '', SAT: '', SUN: '', PHW: '', SAN: '', COMM: '', BON: '', other: '', quantity: '', leaveDays: '', from: '', to: '', reason: '', costCentre: '', message: '' } ]; const mergedArr = mergeDuplicateEmployees(originalArr); console.log(mergedArr);
代码说明
- 如果你的字段空值定义包含
undefined、null等情况,可以调整判断条件适配,比如if (!existing[key] && existing[key] !== 0)避免把数值0误判为空值 - 首次存入Map时浅拷贝原始对象,避免修改原数组数据,如果不需要保留原数组可以直接存
item本身
内容的提问来源于stack exchange,提问作者davepiqch
相关产品推荐
相关产品推荐

