Search code examples
javascriptforeachjavascript-objectsnested-object

iterate through object calculate total number value in nested object


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

Solution

  • 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)