如何用JavaScript对数组对象中name与type属性相同的项求和?
按name和type合并并求和price的实现方法
这需求在数组数据聚合场景里很常见,咱们用JavaScript的Array.reduce()就能轻松搞定,核心思路是通过一个临时容器跟踪已经出现过的name+type组合,遇到匹配项就累加价格,最后把结果转成目标数组即可。
具体代码实现
var obj = [ {name: 'a1', type: 't1', price: 10}, {name: 'a1', type: 't1', price: 10}, {name: 'a2', type: 't2', price: 10}, {name: 'a1', type: 't2', price: 10}, ]; const mergedResult = Object.values(obj.reduce((accumulator, currentItem) => { // 用name和type拼接成唯一标识键,确保只有两者都匹配才会归为同一组 const uniqueKey = `${currentItem.name}-${currentItem.type}`; if (accumulator[uniqueKey]) { // 如果该组合已存在,累加price accumulator[uniqueKey].price += currentItem.price; } else { // 组合不存在则添加新条目,用浅拷贝避免修改原始数据 accumulator[uniqueKey] = {...currentItem}; } return accumulator; }, {})); console.log(mergedResult);
关键逻辑说明
- 唯一分组标识:用
${currentItem.name}-${currentItem.type}作为键,保证只有当name和type完全相同时,才会被识别为同一组。 - 价格累加:遍历数组时,若当前组合已在临时对象中,就把当前项的
price加到已存在项的price上;若不存在,就把当前项的浅拷贝存入临时对象。 - 结果转换:最后用
Object.values()把临时对象的所有值提取出来,转成你需要的数组格式。
运行这段代码就能得到你预期的结果啦~
内容的提问来源于stack exchange,提问作者muimui
相关产品推荐
相关产品推荐

