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

How do I get the sum of two json objects?

This is the json data I have, And I need the sum of ‘homescorepoints’ + ‘homeframepointsadj’ and/or
‘awayscorepoints’ + ‘awayframepointsadj’…

"512830": {
    "compname": "VNEA Vegas League",
    "grade": "",
    "hometeamlabel": "Pool Tang Clan",
    "homeshortlabel": "Pool Tang Clan",
    "awayteamlabel": "All Shades",
    "awayshortlabel": "All Shades",
    "homescore": 11,
    "homescorepoints": "187",
    "homeframepointsadj": "5",
    "awayscore": 14,
    "awayscorepoints": "178",
    "awayframepointsadj": "0",
}

I understand the basic array.reduce for adding multiple occurences of say "awayscore", but I’m have a mental block with adding two separate objects values together.

Can anyone help please 🙂

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

>Solution :

Assuming that you wanted to sum values from this example object: .reduce() accept arrays so, you can use Object.values() method for your object to get the array and than use .reduce() like this:

const jsonData = {
  "512830": {
    "compname": "VNEA Vegas League",
    "grade": "",
    "hometeamlabel": "Pool Tang Clan",
    "homeshortlabel": "Pool Tang Clan",
    "awayteamlabel": "All Shades",
    "awayshortlabel": "All Shades",
    "homescore": 11,
    "homescorepoints": "187",
    "homeframepointsadj": "5",
    "awayscore": 14,
    "awayscorepoints": "178",
    "awayframepointsadj": "0",
  }
};

const calculateScore = (data, type) => 
  Object.values(data).reduce((acc, curr) => 
    acc + parseInt(curr[`${type}scorepoints`]) + parseInt(curr[`${type}framepointsadj`]), 0);

const homeScore = calculateScore(jsonData, 'home');
const awayScore = calculateScore(jsonData, 'away');

console.log(homeScore);
console.log(awayScore);
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