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 🙂
>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);