Javascript:按键减少/聚合的更简洁的方法?
这段代码给出了预期的结果,但是有没有更简洁的方法来实现同样的结果?不过,这只是一个好奇的问题 目标是要有一张地图,代表每所学校的学生总数,以及一张地图,代表每所学校的教师总数Javascript:按键减少/聚合的更简洁的方法?,javascript,arrays,object,ecmascript-6,Javascript,Arrays,Object,Ecmascript 6,这段代码给出了预期的结果,但是有没有更简洁的方法来实现同样的结果?不过,这只是一个好奇的问题 目标是要有一张地图,代表每所学校的学生总数,以及一张地图,代表每所学校的教师总数 // Example data const studentsMap = { student123: { teacher: 'teacher123' }, student456: { teacher: 'teacher123' }, student789
// Example data
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.keys(studentsMap).reduce((totals, key) => {
const current = studentsMap[key];
if (!teachersMap[current.teacher] || !teachersMap[current.teacher].school) {
return totals;
}
totals[teachersMap[current.teacher].school] = (totals[teachersMap[current.teacher].school] || 0) + 1;
return totals;
}, {});
const teachersTotalBySchool = Object.keys(teachersMap).reduce((totals, key) => {
const current = teachersMap[key];
totals[current.school] = (totals[current.school] || 0) + 1;
return totals;
}, {});
有没有一种方法可以在不牺牲太多可读性的情况下更简洁地编写此文档?您可以使用
对象。条目和解构如下:
const studentsTotalBySchool = Object.entries(studentsMap).reduce((totals, [key, { teacher }) => {
if (!teachersMap[teacher] || !teachersMap[teacher].school) return totals;
totals[teachersMap[teacher].school] = (totals[teachersMap[teacher].school] || 0) + 1;
return totals;
}, {});
const teachersTotalBySchool = Object.entries(teachersMap).reduce((totals, [key, { school }) => {
totals[school] = (totals[school] || 0) + 1;
return totals;
}, {});
这将以更少的代码获得相同的结果
let学校={
学校123:{
教师123:{
学生:[“学生123”、“学生456”]
},
教师456:{
学生:[“学生789”]
}
},
456所学校:{
教师123:{
学生:[“学生123”、“学生456”]
},
教师456:{
学生:[“学生789”]
}
}
};
函数findTotal(学校,总计){
设累加=0;
开关(总计){
案例“学生”:
对于(让教师使用Object.key(学校[学校]){
累计+=学校[学校][教师].学生.length;
}
打破
案例“教师”:
累计=对象.键(学校[学校])长度;
}
累积收益;
}
log(findTotal(“school123”、“students”))
日志(findTotal(“school123”、“教师”))
<>代码>站点定位是基于意见的,因此这个问题似乎是基于意见的,请考虑把你的问题移到站点。不确定如何“移动”它。我没有看到前面提到的迁移选项。