为嵌套数组中同键值的对象添加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 } ]
原代码问题说明
- 覆盖统计结果:原代码循环每个子数组时,每次都重新赋值
summary,导致之前的统计结果被覆盖,最终只保留了最后一个子数组的无效统计。 - 不规范的累加器:原代码用数组作为
reduce的初始值,却给数组添加自定义属性(a[k]),这种写法不符合数组的使用规范,改用普通对象作为累加器更直观高效。
内容的提问来源于stack exchange,提问作者suraj
相关产品推荐
相关产品推荐

