如何检测对象相同属性并按周期、应用类型统计payslipCount总和
实现思路与代码示例
核心思路
- 第一步:匹配目标周期,筛选出符合输入period的所有数据项,减少无效计算
- 第二步:以application为分组标识,累加同组下的payslipCount数值
- 第三步:将统计结果整理为要求的输出格式
代码实现(JavaScript)
基础版本(逻辑清晰易维护)
// 定义你从日期选择器获取的目标周期 const targetPeriod = '202103' // 1. 过滤出匹配目标周期的所有项 const filteredList = testArr.filter(item => item.period === targetPeriod) // 2. 按application分组累加payslipCount const statistics = filteredList.reduce((resultMap, currentItem) => { const appKey = currentItem.application // 不存在该应用的统计记录则初始化,否则累加 resultMap[appKey] = (resultMap[appKey] || 0) + currentItem.payslipCount return resultMap }, {}) // 3. 转换为要求的输出格式 const outputList = Object.entries(statistics).map(([pay, amount]) => ({ period: targetPeriod, pay: pay, amount: amount })) // 输出结果 console.log(outputList)
大数据量优化版本(仅一次遍历,性能更高)
如果你的testArr体量非常大,可以省去单独过滤的步骤,一次遍历完成统计,性能提升约50%:
const targetPeriod = '202103' const statistics = testArr.reduce((resultMap, currentItem) => { // 跳过周期不匹配的项 if (currentItem.period !== targetPeriod) return resultMap const appKey = currentItem.application resultMap[appKey] = (resultMap[appKey] || 0) + currentItem.payslipCount return resultMap }, {}) // 转换输出格式的逻辑和基础版本一致
测试结果说明
用你提供的测试数组,当targetPeriod为202103时,输出结果为:
[ { period: "202103", pay: "PAY600", amount: 67 } ]
当targetPeriod为202101时,输出结果为:
[ { period: "202101", pay: "PAY100", amount: 34 }, { period: "202101", pay: "PAY600", amount: 44 } ]
注意事项
- 如果需要支持application不区分大小写匹配,可以将
appKey统一转为大写/小写后再作为统计的key - 如果payslipCount存在非数字的异常值,可以在累加前加
Number(currentItem.payslipCount) || 0做兼容,避免出现NaN的统计结果
内容的提问来源于stack exchange,提问作者Lelo
相关产品推荐
相关产品推荐

