Javascript:按键减少/汇总的更简洁方法?

时间:2019-06-28 21:47:43

标签: javascript arrays object ecmascript-6

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

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

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用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;
}, {});

答案 1 :(得分:0)

这将以更少的代码获得相同的结果

 let schools = {
  school123: {
    teacher123 : {
      students: ["student123", "student456"]
    },
    teacher456 : {
      students: ["student789"]
    }
  },
  school456: {
    teacher123 : {
      students: ["student123", "student456"]
    },
    teacher456 : {
      students: ["student789"]
    }
  }
};

function findTotal(school, totalOf){

  let accumulated = 0;

  switch(totalOf){

    case "students":
      for(let teachers of Object.keys(schools[school])){
        accumulated += schools[school][teachers].students.length;
      }
      break;

    case "teachers":
    accumulated = Object.keys(schools[school]).length;

  }

  return accumulated;

}
console.log(findTotal("school123", "students"))
console.log(findTotal("school123", "teachers"))