这段代码给出了预期的结果,但是有没有更简洁的方法来达到相同的结果呢?不过,这仅仅是出于好奇。

目标是制作一张代表每所学校的学生总数的地图,以及一张代表每所学校的教师总数的地图。

// 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;
}, {});



有没有办法在不牺牲过多可读性的情况下更简洁地编写此内容?

最佳答案

您可以使用Object.entries并进行如下破坏:

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;
}, {});

09-03 23:33