首页 > 解决方案 > 从 JSON 数据(嵌套对象)计算球队的赛季目标

问题描述

如何从以下数据中获取球队本赛季的进球数。其中团队名称是函数输入。

我在尝试映射回合并过滤团队1或团队2 ===输入团队的比赛然后减少这些分数的总和时是否正确?

缩短的数据样本:

{
  "name": "English Premier League 2014/15",
  "rounds": [
    {
      "name": "Matchday 1",
      "matches": [
        {
          "date": "2014-08-16",
          "team1": {
            "key": "manutd",
            "name": "Manchester United",
            "code": "MUN"
          },
          "team2": {
            "key": "swansea",
            "name": "Swansea",
            "code": "SWA"
          },
          "score1": 1,
          "score2": 2
        },
        {
          "date": "2014-08-16",
          "team1": {
            "key": "leicester",
            "name": "Leicester City",
            "code": "LEI"
          },
          "team2": {
            "key": "everton",
            "name": "Everton",
            "code": "EVE"
          },
          "score1": 2,
          "score2": 2
        }, 

到目前为止,我的努力是:

function run (teamName){

    function getSum (total, match) {
        return total + match.score1;
    }


    fetch('https://raw.githubusercontent.com/openfootball/football.json/master/2014-15/en.1.json')
    .then(response => response.json())
    .then(data => console.log(data.rounds.map( matchday => matchday.matches.filter(match => match.team1.name === teamName).reduce(getSum))));

}

run('Liverpool')

标签: javascriptjsonecmascript-6

解决方案


尝试这个

function findScoreByTeamName(strTeamName){

  let jsnLeague = {
    "name": "English Premier League 2014/15",
    "rounds": [
      {
        "name": "Matchday 1",
        "matches": [
          {
            "date": "2014-08-16",
            "team1": {
              "key": "manutd",
              "name": "Manchester United",
              "code": "MUN"
            },
            "team2": {
              "key": "swansea",
              "name": "Swansea",
              "code": "SWA"
            },
            "score1": 1,
            "score2": 2
          },
          {
            "date": "2014-08-16",
            "team1": {
              "key": "leicester",
              "name": "Leicester City",
              "code": "LEI"
            },
            "team2": {
              "key": "everton",
              "name": "Everton",
              "code": "EVE"
            },
            "score1": 2,
            "score2": 2
          }
        ]
      }
    ]
  };

  let score = 0;

  for(round of jsnLeague.rounds){
      for(match of round.matches){
          if(match.team1.name == strTeamName){
              score += match.score1;
          }else if(match.team2.name == strTeamName){
              score += match.score2;
          }
      }
  }

  console.log(score);

}

//Then call it
findScoreByTeamName("Swansea");

我已经在这里测试了代码,复制粘贴并看看

希望能帮助到你!


推荐阅读