javascript - 从 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')
解决方案
尝试这个
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");
我已经在这里测试了代码,复制粘贴并看看
希望能帮助到你!
推荐阅读
- javascript - 将 UDP 数据包从一个端口转发到另一个端口
- typescript - TypeScript “lib” 选项的真正作用是什么?
- c# - 获取服务 .net 核心中的 appsettings.json 值
- react-native - 如何在 react-Native 中使用 Tab Navigation 传递数据?(反应导航)?
- google-api - 我们可以通过我们的 ACCESS_TOKEN 获取其他人的信息吗
- angular - angular 5 应用程序是否有第三方日期选择器
- c# - Xamarin EF Core 数据播种
- office-js - Office Web 插件 - 我可以动态更改任务窗格标题吗?
- php - Laravel 5.6.26 错误 - 找不到类“Tymon\JWTAuth\Providers\LaravelServiceProvider”
- angular - Angular:显示具有多个接口的 JSON API 调用