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

JavaScript过滤嵌套对象数组并按type分组统计数量

原代码存在的问题

你写的代码有3个核心错误,导致拿不到正确结果:

  • 数据层级访问错误:你的原始数据是多层嵌套结构,vehicles数组存放在每个日期项的report子数组元素下,直接在最外层数组项上取element.vehicles会得到undefined,根本访问不到车辆数据。
  • 状态判断逻辑错误:if (element.status === 'oos' || 'pm') 是典型的JS逻辑笔误,||后的非空字符串'pm'是恒真值,这个判断不管status是什么都会返回true,完全起不到过滤作用。
  • 逻辑缺失:只写了半截过滤逻辑,没有实现后续按type字段分组统计数量的步骤。
修正后的完整代码

按照「提取所有车辆 -> 过滤符合状态要求的项 -> 分组计数」的流程实现即可,兼容你当前的Angular/TS写法:

getReport() {
  this.backend.getAnalyticsReport().subscribe(
    response => {
      console.log(this.processReport(response))
    }
  )
}

processReport(sourceData: any[]) {
  // 扁平化取出所有嵌套层级下的车辆数据
  const allVehicles = sourceData.flatMap(dateEntry => 
    dateEntry.report.flatMap(reportEntry => reportEntry.vehicles)
  )

  // 过滤状态为oos或pm的车辆
  const validVehicles = allVehicles.filter(vehicle => {
    return ['oos', 'pm'].includes(vehicle.status)
  })

  // 按type分组统计总数
  const statResult = validVehicles.reduce((stat, vehicle) => {
    const vehicleType = vehicle.type
    stat[vehicleType] = (stat[vehicleType] || 0) + 1
    return stat
  }, {} as Record<string, number>)

  return statResult
}
运行结果说明

传入你给出的示例数据运行上述代码,最终返回的统计结果为:

{ bus: 2 }

完全符合你的预期。

如果需要适配不支持flatMap的老旧运行环境,把扁平化提取车辆的步骤换成普通for循环遍历即可,逻辑完全一致。另外后续判断多值匹配的场景,优先用数组+includes的写法,避免出现a === x || y这类低级笔误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 17:42:23