skip to Main Content

I want to iterate through the objects and calculate a total sum of all the values that appear to be in a nested object. I don’t appear to be able to get the number value on its own.

const drunks = {
  'Cheryl': { numberOfDrinks: 10 },
  'Jeremy': { numberOfDrinks: 4 },
  'Gordon': { numberOfDrinks: 2 },
  'Laura': { numberOfDrinks: 6 }
}

let totalDrunks = 0
let numberOfDrunks = Object.values(drunks)

numberOfDrunks.forEach((drink) => {
totalDrunks += drunks[drink];
})
console.log (totalDrunks) //Expecting a number value of 22

4

Answers


  1. There are a few ways to loop through objects. I prefer not to convert to an array just iterate using for in instead.

    So here I’m loop through the object and then getting numberOfDrinks on each element.

    const drunks = {
      'Cheryl': { numberOfDrinks: 10 },
      'Jeremy': { numberOfDrinks: 4 },
      'Gordon': { numberOfDrinks: 2 },
      'Laura': { numberOfDrinks: 6 }
    }
    
    let totalDrunks = 0
    
    for(let drink in drunks){
      totalDrunks+= drunks[drink].numberOfDrinks;
    }
    
    console.log(totalDrunks)
    Login or Signup to reply.
  2. Replace line:

    totalDrunks += drunks[drink];  
    

    To

    totalDrunks += drink.numberOfDrinks;
    
    Login or Signup to reply.
  3. The issue is that when you are using Object.values(drunks), you are getting an array of objects as a result. In your forEach loop, drink will represent each object from the array, not the actual number value of numberOfDrinks.

    To fix this, you need to access the numberOfDrinks property of each object in the loop and add it to the totalDrunks variable. Here’s the corrected code:

    const drunks = {
      'Cheryl': { numberOfDrinks: 10 },
      'Jeremy': { numberOfDrinks: 4 },
      'Gordon': { numberOfDrinks: 2 },
      'Laura': { numberOfDrinks: 6 }
    }
    
    let totalDrunks = 0;
    let numberOfDrunks = Object.values(drunks);
    
    numberOfDrunks.forEach((drink) => {
      totalDrunks += drink.numberOfDrinks; // Access the numberOfDrinks property of each object
    });
    
    console.log(totalDrunks); // Output: 22

    Now, the totalDrunks variable will correctly hold the total sum of the numberOfDrinks property from each object in the drunks object.

    Login or Signup to reply.
  4. If you want to use a more functional approach you could also use reduce().

    const drinks = {
      'Cheryl': { numberOfDrinks: 10 },
      'Jeremy': { numberOfDrinks: 4 },
      'Gordon': { numberOfDrinks: 2 },
      'Laura': { numberOfDrinks: 6 }
    }
    
    const totalDrinks = Object.values(drinks)
      .reduce((total, person) => total += person.numberOfDrinks, 0);
    
    console.log(totalDrinks)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search