I created a function that uses the method Object.keys(myObj) to generate a random key from its array. I want to use the value returned by the variable currentCountry to grab the corresponding value from the matching key/value pair in my object.
I tried directly substituting the variable name in to try and call the method that way (countryObj.currentCountry), but that came back 'undefined'
I've done a good bit of Google searching but so far haven't found what I need to do this.
let countryObj = {
Argentina: 'buenos Aires',
Bolivia: 'Sucre',
Brazil: 'Brasilia',
Chile: 'Santiago',
Columbia: 'Bogotá',
Ecuador: 'Quito',
Guyana: 'Georgetown',
Paraguay: 'Asunción',
Peru: 'Lima',
Suriname: 'Paramaribo',
Uruguay: 'Montevideo',
Venezuela: 'Caracas'
}
let keys = Object.keys(countryObj); // returns an array of the keys (country names) in countryObj
let currentCountry = "";
let randomCountry = function() { // returns a randomly chosen country from the keys array and writes
// ... the country to the <p> element in index.html
currentCountry = keys[Math.floor(keys.length * Math.random())];
document.getElementById('p').innerHTML = currentCountry;
return currentCountry;
When I tried directly subbing the variable name to call the method it returned 'undefined'