Josh Cawthorne Josh Cawthorne - 1 month ago 9
jQuery Question

Search JSON array for matching string and then work upward?

I'm trying to search an Array for a matching team name and then work upward to get the data for an entire match, however I'm unsure how to do so. The JSON array looks like the following:

{
"name": "English Premier League 2016/17",
"rounds": [
{
"name": "Matchday 1",
"matches": [
{
"date": "2017-05-21",
"team1": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"team2": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"score1": 1,
"score2": 2
},
{
"date": "2017-05-21",
"team1": {
"key": "watford",
"name": "Watford",
"code": "WAT"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 2,
"score2": 1
}
]
}
]
}


At the moment, my code is as follows, however it says it can't read property 'team1' of undefined.

var team = Swansea;

$.getJSON("https://raw.githubusercontent.com/opendatajson/football.json/master/2016-17/en.1.json", function(results) {
for(var i = 0; i < results.rounds.length; i++)
{
if(results.rounds[matchday].matches[i].team1.name == team)
{
console.log(results.rounds[matchday].matches.team1.name);
}
}
}

Dij Dij
Answer Source

you can do something like this:

var team = Swansea;

$.getJSON("https://raw.githubusercontent.com/opendatajson/football.json/master/2016-17/en.1.json", function(results) { 
       for(var i = 0; i < results.rounds.length; i++)
        {
          for (var j=0; j< results.rounds[i].matches.length; j++){
             if(results.rounds[i].matches[j].team1.name == team)
             {
                console.log(results.rounds[i].matches[j].team1.name);
             } 
             if (results.rounds[i].matches[j].team2.name == team){
                console.log(results.rounds[i].matches[j].team2.name);
             }
          }
        }
    }