如何向所有学生添加新的属性“注释”并返回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注释?
答案 0 :(得分:3)
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)
答案 1 :(得分:0)
您可以像这样使用for..of
循环
ClassFoo = {
"Total": 3,
"students": [{
"name": "Peter",
"grade": "C"
},
{
"name": "Ben",
"grade": "B"
},
{
"name": "Ann",
"grade": "B"
},
]
};
for (let student of ClassFoo.students) {
if (student.grade === 'B') {
student.comment = 'good';
} else if (student.grade === 'C') {
student.comment = 'work harder';
}
}
console.log(ClassFoo)
for..of
循环将遍历students数组中的每个元素,并在学生对象上添加值为'good'的属性注释。