iterate through object calculate total number value in nested object

70 Views Asked by At

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

There are 4 best solutions below

1
imvain2 On BEST ANSWER

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)

0
Ashish On

Replace line:

totalDrunks += drunks[drink];  

To

totalDrunks += drink.numberOfDrinks;
0
AdityaDees On

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.

0
Mushroomator On

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)