如何提取数组对象中相同属性项并累加对应sold字段的数值
针对指定条件的累加实现(匹配matri=1且year=2020)
先通过filter方法筛选符合条件的所有条目,再用reduce方法累加所有匹配条目的sold字段值即可,代码示例:
const sold = [ { matri: 1, year: 2019, sold: 5 }, { matri: 2, year: 2020, sold: 3 }, { matri: 1, year: 2020, sold: 7 }, ]; // 筛选符合条件的条目 const matchedList = sold.filter(item => item.matri === 1 && item.year === 2020); // 累加sold字段值 const sumSold = matchedList.reduce((total, current) => total + current.sold, 0); console.log(sumSold) // 输出结果:12
通用多属性分组累加实现
如果需要批量处理所有matri和year的相同组合,无需逐个指定筛选条件,可以直接用reduce做分组统计,代码示例:
const sold = [ { matri: 1, year: 2019, sold: 5 }, { matri: 2, year: 2020, sold: 3 }, { matri: 1, year: 2020, sold: 7 }, ]; // 以matri+year作为分组唯一标识 const groupResult = sold.reduce((acc, item) => { const groupKey = `${item.matri}-${item.year}`; if (!acc[groupKey]) { acc[groupKey] = { ...item, sold: 0 }; } acc[groupKey].sold += item.sold; return acc; }, {}); // 转换为数组格式输出 const finalResult = Object.values(groupResult); console.log(finalResult) /* 输出结果: [ { matri: 1, year: 2019, sold: 5 }, { matri: 2, year: 2020, sold: 3 }, { matri: 1, year: 2020, sold: 12 } ] */
内容的提问来源于stack exchange,提问作者Idriss
相关产品推荐
相关产品推荐

