JavaScript中按对象属性分组并统计数量的实现方案
JavaScript: 按指定属性列表分组并统计每组数量
问题描述
我有一个嵌套结构的对象数组temp,想要根据传入的属性列表(比如["gender","status"]),分别按每个属性分组并统计每组的数量。
示例数组:
const temp = [ { properties: { "id":1234, "gender": 'male', "status": "Active" } }, { properties: { "id":1456, "gender": 'male', "status": "Not Active" } }, { properties: { "id":1377, "gender": 'female', "status": "Active" } }, { properties: { "id":8799, "gender": 'female', "status": "Active" } } ];
我尝试实现了groupFunc函数但有问题,期望得到的分组统计结果如下:
grouped = [ [ { "key": "gender", "value": "male", "count": 2 }, { "key": "gender", "value": "female", "count": 2 } ], [ { "key": "status", "value": "Active", "count": 3 }, { "key": "status", "value": "Not Active", "count": 1 } ] ]
解决方案
这里给你两种实现方式,都能精准满足你的需求:
方式一:逻辑直观的forEach写法
这种写法步骤清晰,新手也能快速理解:
function groupFunc(attributes) { // 遍历每个需要统计的属性,生成对应分组结果 return attributes.map(attr => { const countMap = {}; // 遍历原数组,统计当前属性每个值的出现次数 temp.forEach(item => { const value = item.properties[attr]; countMap[value] = (countMap[value] || 0) + 1; }); // 将计数对象转换为期望的数组格式 return Object.entries(countMap).map(([value, count]) => ({ key: attr, value, count })); }); } // 测试调用 const grouped = groupFunc(["gender", "status"]); console.log(grouped);
方式二:简洁的reduce函数式写法
如果喜欢更紧凑的代码风格,可以用reduce简化统计逻辑:
function groupFunc(attributes) { return attributes.map(attr => { // 用reduce一次性生成计数映射 const countMap = temp.reduce((acc, item) => { const value = item.properties[attr]; acc[value] = (acc[value] || 0) + 1; return acc; }, {}); // 转换为目标格式 return Object.entries(countMap).map(([value, count]) => ({ key: attr, value, count })); }); }
核心逻辑说明
- 逐个处理属性:通过
map遍历传入的属性列表,为每个属性单独生成统计结果,保证结果数组的结构和属性列表顺序一致。 - 高效计数:用临时对象
countMap存储每个属性值的出现次数,只需要遍历原数组一次就能完成单个属性的统计。 - 格式转换:
Object.entries把对象的键值对转换成数组,再通过map映射成你需要的{key, value, count}结构,完美匹配期望输出。
这两种方式都能输出你想要的结果,选自己看着顺眼的用就行~
内容的提问来源于stack exchange,提问作者ReNinja
相关产品推荐
相关产品推荐

