javascript更新对象数组中的所有值

时间:2018-11-06 20:36:04

标签: javascript arrays object

如何向所有学生添加新的属性“注释”并返回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注释?

2 个答案:

答案 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'的属性注释。