0

I am trying to 'join' two arrays on a key value.

The first array:

    "matches": [
           {
           "name": 33,
           "home_team": 4,
           "away_team": 1,
           "home_result": 3,
           "away_result": 0
           },
           {
             ...
           }
           ]

The second array:

  "teams": [
        {
            "id": 1,
            "name": "Russia"
        },
        {
          ...
        }
]

When looping through matches, I would like to join the home_team id with the respective team id and display teams[i].name instead of the id. The same for away_team.

I tried the following but it does not work:

var mymatches = [];
for (i=0;i<matches.length;i++) {
   var h = matches[i].home_team;
   var a = matches[i].away_team;
    var mymatch = {
      name: matches[i].name,
      home_team: teams[h].name,
      away_team: teams[a].name

    };
   mymatches.push(mymatch);

}

When loggin variables a and h, the correct number is being output, however it is not being accepted in the [] part, which I find strange as it works with [i] in a for loop...

The full data is from a JSON file available below. I know that the matches array is nested within a "groups" object, however I was able to 'unnest' the "matches" arrays:

https://github.com/lsv/fifa-worldcup-2018/blob/master/data.json

3
  • Take a look at this post: https://stackoverflow.com/questions/22593515/analog-to-sql-join-for-javascript-objects Commented Jul 9, 2018 at 4:34
  • Desired output: "matches": [ { "name": 33, "home_team": Uruguay, "away_team": Russia, "home_result": 3, "away_result": 0 }, Commented Jul 9, 2018 at 4:35
  • You should do some changes to your code first you should add Number function to parse to integer in this line var h = matches[i].home_team; and var a = matches[i].away_team; you use var h = Number(matches[i].home_team); and the same for the other to get an integer variable and not string, second thing is that when you create mymatch variable you should add quoutes to name and home_team and away_team like 'name' and 'home_team' and 'away_team'. Commented Jul 9, 2018 at 4:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.