You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按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)

原代码问题说明

  1. 你声明了violations为数组,却用字符串作为key赋值,数组的字符串key不会被识别为数组成员,后续无法正常遍历获取结果,应该用普通对象作为中间分组容器。
  2. 没有判断key对应的分组是否存在就直接给violations[key]的属性赋值,会抛出Cannot set properties of undefined的报错。
  3. 缺少核心的value累加逻辑,只赋值了司机和公司标识,没有统计各事件类型的value总和。

内容的提问来源于stack exchange,提问作者Deep Kakkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:15:03