改善嵌套属性的循环-javascript

时间:2018-12-26 09:34:45

标签: javascript lodash

尝试根据嵌套的属性值过滤学生。 基本上每个学生对象都具有数组类型的属性:studentSuperSubject 依次将数组作为属性:studentSubSubjectOrSkill subjects是具有以下形式的对象数组: {superSubject: "some super subject name", subSubject: "some sub subject name"}subSubject中的每个studentSubSubjectOrSkill都具有属性studentSubSubjectScore,这是我正在寻找的属性。 我想遍历subjects中每个主题的students数组,然后创建并存储对象,然后将其存储到另一个数组-grades=[]

我设法用看起来像意大利面条的休·哈尔大喊大叫的方式完成了任务:

  for (let subject of subjects) {
    var grades = [];
    this.data.students.filter(student => {
      let name = student.studentName;

      // loop over each student > superSubject > subSubject
      for (let superSubject of student.studentSuperSubject) {
        if (superSubject.superSubjectName === subject.superSubject) {
          superSubject.studentSubSubjectOrSkill.filter(sub => {
            if (sub.subSubjectName === subject.subSubject) {
              grades.push({
                name: name,
                pass: sub.studentSubSubjectScore > 58
              });
              return;
            }
          });
        }
      }
    });
    subject["grades"] = grades;
  }

有什么想法可以改善这一点,以使将来使用此代码的开发人员的工作更轻松? 作为旁注,lodash在此项目中可用 谢谢。

2 个答案:

答案 0 :(得分:0)

1 /您未正确使用过滤器,该过滤器在您要返回数组的子集时应使用,当您要对数组的每个元素执行操作时应使用map

2 / for ... of ...用于遍历值,for ... in ...属性上

3 /我认为这样更具可读性:

for (let subject of subjects) {
    var grades = [];

    this.data.students.map(student => {
      let name = student.studentName;

      student.studentSuperSubject
          .filter(superSubject => superSubject.superSubjectName === subject.superSubject)
          .map(superSubject=> {                     
              superSubject.studentSubSubjectOrSkill
                  .filter(sub => sub.subSubjectName === subject.subSubject)
                  .map(sub=>{
                      grades.push({
                          name: name,
                          pass: sub.studentSubSubjectScore > 58
                      });
                  });
          });
      });

   subject["grades"] = grades;
}

答案 1 :(得分:0)

为了便于阅读,我会一次检查一件事并添加一些评论。

// Iterates for all subjects.
subjects.forEach(subject => {
    // Subject grades.
    subject.grades = [];

    // Iterates for all the students.
    students.forEach(student => {
        // Finds and validates the student super subject.
        var studentSuperSubject = student.studentSuperSubject.find(superSubject => superSubject.superSubjectName === subject.superSubject);
        if (!studentSuperSubject) return;

        // Finds and validates the student sub subject.
        var studentSubSubject = studentSuperSubject.studentSubSubjectOrSkill.find(subSubject => subSubject.subSubjectName == subject.subSubject);
        if (!studentSubSubject) return;

        // Saves the student grade.
        subject.grades.push({
            name: student.studentName,
            pass: studentSubSubject.studentSubSubjectScore > 58
        });
    });
});