如何在JavaScript对象数组中按相同key合并对象并添加对应键值对
核心问题
原有代码的两处错误:
- 字段名不匹配:原数组对象的属性为
company、product、sell,代码中误用了不存在的name、value、count字段 - 逻辑错误: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
相关产品推荐
相关产品推荐

