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
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.To
The issue is that when you are using
Object.values(drunks)
, you are getting an array of objects as a result. In yourforEach
loop,drink
will represent each object from the array, not the actual number value ofnumberOfDrinks
.To fix this, you need to access the
numberOfDrinks
property of each object in the loop and add it to thetotalDrunks
variable. Here’s the corrected code:Now, the
totalDrunks
variable will correctly hold the total sum of thenumberOfDrinks
property from each object in thedrunks
object.If you want to use a more functional approach you could also use
reduce()
.