Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading