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

为嵌套数组中同键值的对象添加count属性(JavaScript)

解决嵌套数组的对象统计问题

核心思路

先将嵌套数组扁平化(把所有子数组中的对象合并为一维数组),再通过reduce统计具有相同apiName和error值的对象数量。

完整代码实现

const arr = [
  [{ apiName: 'app/abc', error: '', res: 'response' }],
  [{ apiName: 'app/abc', error: '', res: 'response' }],
  [{ apiName: 'app/abc', error: '', res: 'response' }],
  [{ apiName: 'app/abc', error: 'error\'s', res: 'response' }],
  [{ apiName: 'app/abc', error: 'no error\'s', res: 'response' }],
  [{ apiName: 'app/abc', error: 'no error\'s', res: 'response' }],
  [{ apiName: 'app/abc', error: '', res: 'response' }],
];

// 1. 扁平化嵌套数组
const flatArr = arr.flat();
// 兼容旧JS环境的写法:const flatArr = [].concat(...arr);

// 2. 统计相同apiName+error组合的数量
const summary = Object.values(flatArr.reduce((acc, { apiName, error }) => {
  // 生成唯一标识键,区分不同组合
  const key = `${apiName}_${error}`;
  // 首次遇到该组合时,初始化统计对象
  if (!acc[key]) {
    acc[key] = { apiName, error, count: 0 };
  }
  // 计数累加
  acc[key].count++;
  return acc;
}, {}));

console.log(summary);

输出结果

[
  { apiName: 'app/abc', error: '', count: 4 },
  { apiName: 'app/abc', error: 'error\'s', count: 1 },
  { apiName: 'app/abc', error: 'no error\'s', count: 2 }
]

原代码问题说明

  1. 覆盖统计结果:原代码循环每个子数组时,每次都重新赋值summary,导致之前的统计结果被覆盖,最终只保留了最后一个子数组的无效统计。
  2. 不规范的累加器:原代码用数组作为reduce的初始值,却给数组添加自定义属性(a[k]),这种写法不符合数组的使用规范,改用普通对象作为累加器更直观高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:42:55