如何向所有学生添加新的属性“注释”并返回ClassFoo?

ClassFoo = {
    "Total": 3,
    "students": [
        {
            "name": "Peter",
            "grade": "C"
        },
        {
            "name": "Ben",
            "grade": "B"
        },
        {
            "name": "Ann",
            "grade": "B"
        },
    ]
};

Comments(B) = {
    "grade": "B",
    "comment": "Good"
};

Comments(C) = {
    "grade": "C",
    "comment": "Work harder"
};


变成这样

ClassFoo = {
    "Total": 3,
    "students": [
        {
            "name": "Peter",
            "grade": "C",
            "comment": "Work harder"
        },
        {
            "name": "Ben",
            "grade": "B",
            "comment": "Good"
        },
        {
            "name": "Ann",
            "grade": "B",
            "comment": "Good"
        },
    ]
};


我应该创建一个新对象吗?
对ClassFoo.students使用.map?
然后如果Comment.grade === ClassFoo.students.grade匹配注释,则.push注释?

最佳答案

class ClassFoo {
  constructor(students) {
    this.total = students.length
    this.students = students
    this.students.forEach(student => {
      if (this.Comments[student.grade]) {
        student.comment = this.Comments[student.grade]
      }
    });
  }

  get Comments() {
    return {
      B: 'Good',
      C: 'Work Harder',
    }
  }
}

const classFoo = new ClassFoo([
  {
    "name": "Peter",
    "grade": "C"
  },
  {
    "name": "Ben",
    "grade": "B"
  },
  {
    "name": "Ann",
    "grade": "A"
  },
]);

console.log(classFoo)

07-26 03:30