如何计算嵌套对象中各班级的所有学期学生总数?
技术解决方案:计算嵌套对象中班级学生总数
问题分析
你当前代码无法得到预期结果的核心原因是:直接对普通对象使用了数组的reduce方法。reduce是数组原型的方法,仅能用于数组遍历,无法直接处理键值对结构的对象。
正确实现思路
要完成需求,需要逐层遍历嵌套的对象结构:
- 遍历目标班级(254、251)
- 对每个班级,遍历其下所有学期的数据
- 对每个学期,遍历内部的学生条目,累加
Students字段的值
代码实现
基础版本(清晰易懂)
const data = { "254": { "Term 1": { 0: { id: 1, Students: 29 }, 1: { id: 1, Students: 20 }, 2: { id: 1, Students: 11 } }, "Term 2": { 0: { id: 1, Students: 9 }, 1: { id: 1, Students: 10 }, 2: { id: 1, Students: 22 } } }, "251": { "Term 1": { 0: { id: 1, Students: 2 }, 1: { id: 1, Students: 5 }, 2: { id: 1, Students: 10 } } } }; // 指定需要计算的班级ID const targetClassIds = ['254', '251']; const classTotal = {}; targetClassIds.forEach(classId => { let total = 0; // 获取当前班级的所有学期数据 const terms = Object.values(data[classId]); terms.forEach(term => { // 遍历学期内的每个学生条目,累加人数 total += Object.values(term).reduce((acc, item) => acc + item.Students, 0); }); classTotal[classId] = total; }); // 输出预期格式的结果 console.log(`- 班级254:所有学期学生总数为${classTotal['254']}`); console.log(`- 班级251:所有学期学生总数为${classTotal['251']}`);
简洁版本(链式调用)
如果追求代码简洁,可以用嵌套的reduce和flatMap实现:
const targetClassIds = ['254', '251']; const classTotal = targetClassIds.reduce((acc, classId) => { acc[classId] = Object.values(data[classId]) // 把所有学期的学生条目合并为一个数组 .flatMap(term => Object.values(term)) // 累加所有学生数 .reduce((sum, item) => sum + item.Students, 0); return acc; }, {}); // 输出结果 console.log(`- 班级254:所有学期学生总数为${classTotal['254']}`); console.log(`- 班级251:所有学期学生总数为${classTotal['251']}`);
关键知识点
Object.values(obj):将对象的所有值提取为数组,方便后续用数组方法处理flatMap:先映射再扁平化数组,把多层嵌套的学生条目合并为一维数组- 数组
reduce:用于累加数值,是处理求和场景的常用方法
内容的提问来源于stack exchange,提问作者Jazz
相关产品推荐
相关产品推荐

