susu watari
susu watari

Reputation: 207

javascript update all values in array of objects

How to add a new property "comment" to all the students and return the 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"
};

Become like this

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

Should I create a new object? use .map for ClassFoo.students? and then match comments if Comments.grade === ClassFoo.students.grade, then .push comment?

Upvotes: 1

Views: 4048

Answers (2)

Willem van der Veen
Willem van der Veen

Reputation: 36620

You can use a for..of loop like this

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)

A for..of loop will iterate over every element in the students array and add a property comment with the value of 'good' on a student object.

Upvotes: 0

Callam
Callam

Reputation: 11539

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)

Upvotes: 3

Related Questions