JavaScript:如何更简洁实现按键聚合归约且兼顾可读性?
更简洁实现学校师生总数统计映射的方案
你提到现有代码能正常工作,但想找更简洁且不丢可读性的写法——完全可以!咱们利用ES6+的语法特性来优化,既缩短代码,又让逻辑更清晰。
先明确需求:基于给定的studentsMap和teachersMap,生成两个统计映射:
- 各学校的学生总数
- 各学校的教师总数
优化后的实现代码
// 示例数据 const studentsMap = { student123: { teacher: 'teacher123' }, student456: { teacher: 'teacher123' }, student789: { teacher: 'badID' }, student000: {} }; const teachersMap = { teacher123: { school: 'school123' }, teacher456: { school: 'school123' }, teacher789: { school: 'school456' } }; // 各学校学生总数映射 const studentsTotalBySchool = Object.entries(studentsMap).reduce((totals, [_, student]) => { const school = teachersMap[student.teacher]?.school; if (school) { totals[school] = (totals[school] ?? 0) + 1; } return totals; }, {}); // 各学校教师总数映射 const teachersTotalBySchool = Object.entries(teachersMap).reduce((totals, [_, teacher]) => { totals[teacher.school] = (totals[teacher.school] ?? 0) + 1; return totals; }, {});
优化点说明
- 用
Object.entries()代替Object.keys():直接获取键值对,不用再通过key去原对象取值,少了一层属性访问,代码更直观。 - 可选链操作符
?.:代替原来的多层判断!teachersMap[current.teacher] || !teachersMap[current.teacher].school,一行就能安全获取学校ID,避免报错的同时更简洁。 - 空值合并运算符
??:比||更精准,只在值为null/undefined时才取默认值0,不会把0、''等有效值误判。 - 解构赋值:在
reduce的回调里直接解构出student和teacher变量,不用再定义current临时变量,减少冗余。
这样写下来,代码比原来短,逻辑却更清晰,完全没牺牲可读性~
内容的提问来源于stack exchange,提问作者Ryan Callens
相关产品推荐
相关产品推荐

