Skip to content Skip to sidebar Skip to footer

Self Reference In Object Literals

How do I find the average score between the 2 games in each week? var scores = { week1: { game1 : 55, game2 : 62, average: ? }, week2: { game1

Solution 1:

You can use a for... in statement to iterate through the properties of the object and calculate the average individually by summing the scores for game1 and game2 and dividing by 2.

var scores = {
  week1: {
    game1: 55,
    game2: 62,
  },
  week2: {
    game1: 71,
    game2: 67
  }
};

for (const x in scores) scores[x].average = (scores[x].game1 + scores[x].game2) / 2;

console.log(scores);

Post a Comment for "Self Reference In Object Literals"