0

I have a JSON file which contains football teams from every country. Example:

var FootballTeams = {  
   "Spain":[  
      "RealMadrid",
      "Barcelona",
      "Valencia"
   ],
   "England":[  
      "ManchesterCity",
      "Arsenal",
      "Chelsea",
      "ManchesterUnited",
      "Liverpool"
   ]
};

My program receives an user input with the country name, and I randomly give them a team from the selected country, as follows:

var SelectedCountry= $('#UserInput').val(); // "Spain" or "England"
alert(FootballTeams.SelectedCountry[Math.floor(Math.random()*FootballTeams.countryf.length)]);

It doesn't seem to be working, though I can access the array if I insert the string directly:

alert(FootballTeams."Spain"[Math.floor(Math.random()*FootballTeams.countryf.length)]);

How is it possible to make the first option work ?

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

2

You shoud try like this when accessing a key of object using variable.

alert(FootballTeams[SelectedCountry][Math.floor(Math.random()*FootballTeams.countryf.length)]);
Mritunjay
  • 25,338
  • 7
  • 55
  • 68