如何获取两个 json 对象的总和?

问题描述 投票:0回答:1

这是我有的json数据。我需要 'homescorepoints' + 'homeframepointsadj' 和/或 '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",
}

了解基本数组。减少添加多次出现的说“awayscore”,但我有一个心理障碍将两个单独的对象值添加在一起。

reactjs arrays json reduce
1个回答
0
投票

假设您想对这个示例对象的值求和:.reduce() 接受数组,那么您可以对对象使用 Object.values() 方法来获取数组,而不是像这样使用 .reduce():

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

© www.soinside.com 2019 - 2024. All rights reserved.