如何按company/driver组合标识对对象数组特定message类型的value值求和
实现代码
// 预定义所有合法的事件类型,用于初始化默认值 const EVENT_TYPES = [ 'CreateHarshAccelerationEvent', 'CreateHarshDecelerationEvent', 'CreateSpeedingEvent', 'CreateIdlingEvent' ] // 用对象做中间分组容器,key为 company/driver 组合 const groupMap = {} for (const item of violation) { // 跳过缺少公司/司机标识的无效数据 if (!item.company || !item.driver) continue const groupKey = `${item.company}/${item.driver}` // 分组不存在则先初始化 if (!groupMap[groupKey]) { groupMap[groupKey] = { driver: item.driver, company: item.company } // 所有事件类型初始累计值设为0 EVENT_TYPES.forEach(eventType => { groupMap[groupKey][eventType] = 0 }) } // 累加当前事件对应的value值 groupMap[groupKey][item.message] += item.value } // 转换为你需要的数组结构 const statisticsResult = Object.values(groupMap) console.log(statisticsResult)
原代码问题说明
- 你声明了
violations为数组,却用字符串作为key赋值,数组的字符串key不会被识别为数组成员,后续无法正常遍历获取结果,应该用普通对象作为中间分组容器。 - 没有判断key对应的分组是否存在就直接给
violations[key]的属性赋值,会抛出Cannot set properties of undefined的报错。 - 缺少核心的value累加逻辑,只赋值了司机和公司标识,没有统计各事件类型的value总和。
内容的提问来源于stack exchange,提问作者Deep Kakkar
相关产品推荐
相关产品推荐

