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

前端项目中按label合并数组对象:同属性值累加,异属性复制

按Label合并数组对象并累加属性值的解决方案

嘿,这个场景我之前做报表统计的时候刚好遇到过,给你分享一个实用的实现思路,用JavaScript的reduce就能轻松搞定~

先明确下核心需求:

  • 以label属性为唯一标识,合并所有label相同的对象
  • 相同属性(比如published、draft)的值要累加,不同属性直接保留
  • 最终结果里不需要保留id这类无关属性

输入示例

const inputArr = [
  { label: 'label-1', published: 1, draft: 2, id: 'some1' },
  { label: 'label-1', published: 2, status: 0, draft: 1, id: 'some4' },
  { label: 'label-2', published: 1, draft: 14, id: 'some2' },
  { label: 'label-2', published: 12, status: 0, draft: 14, id: 'some3' }
];

期望输出

[
  { label: 'label-1', published: 3, draft: 4, status: 0 },
  { label: 'label-2', published: 13, draft: 28, status: 0 }
]

实现代码

const mergedArr = Object.values(inputArr.reduce((acc, curr) => {
  const labelKey = curr.label;
  // 初始化当前label对应的合并对象
  if (!acc[labelKey]) {
    acc[labelKey] = { label: labelKey };
  }
  // 遍历当前对象的所有属性
  for (const prop in curr) {
    // 跳过不需要保留的id属性(如果需要保留可删除此行)
    if (prop === 'id') continue;
    // 处理属性:已存在则累加,不存在则直接复制
    if (acc[labelKey].hasOwnProperty(prop)) {
      // 确保是数字类型再累加,避免非数字值导致异常
      if (typeof acc[labelKey][prop] === 'number' && typeof curr[prop] === 'number') {
        acc[labelKey][prop] += curr[prop];
      }
    } else {
      acc[labelKey][prop] = curr[prop];
    }
  }
  return acc;
}, {}));

代码逻辑拆解

  1. 分组初始化:用reduce遍历输入数组,以label作为键在累加器acc中创建分组,初始只保留label属性
  2. 属性处理:遍历当前对象的每个属性,跳过id;如果分组中已有该属性且为数字类型,就累加值;否则直接复制属性
  3. 结果转换:最后用Object.values把累加器的键值对转换为数组,就是我们需要的合并结果

如果后续需要处理非数字属性的合并(比如字符串拼接),只需要修改属性判断的逻辑就行,灵活性很高~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:18:27