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

如何在JavaScript对象数组中按相同key合并对象并添加对应键值对

核心问题

原有代码的两处错误:

  1. 字段名不匹配:原数组对象的属性为company、product、sell,代码中误用了不存在的name、value、count字段
  2. 逻辑错误:else块中匹配到的found是普通对象,不是数组,没有push方法,直接给对象追加属性即可

正确实现代码

const arr = [{"company":"Google","product":"A","sell":34},{"company":"Google","product":"B","sell":31},{"company":"Google","product":"C","sell":64},{"company":"Twitter","product":"A","sell":34},{"company":"Twitter","product":"B","sell":56},{"company":"Twitter","product":"C","sell":48}]

const result = arr.reduce((acc, d) => {
    const found = acc.find(a => a.company === d.company);
    if (!found) {
        acc.push({ company: d.company, [d.product]: d.sell })
    } else {
        found[d.product] = d.sell;
    }
    return acc;
}, []);

console.log(result)

输出结果

执行后即可得到预期格式:
[{ company: "Google", A: 34, B:31, C:64 },{ company: "Twitter", A: 34, B:56, C:48 }]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:45:01