CzechCoder
CzechCoder

Reputation: 117

Restcountries API - getting names of currencies dynamically into HTML through Javascript

I am new to Javascript and I've been learning how to import a country's attributes into an HTML element. Some of you might recognize this code, it's from a tutorial, which is now outdated. I've been searching around for an updated solution, but couldn't find any.

First I have the function to fetch the data:

const getCountryData = function (country) {
  fetch(`https://restcountries.com/v3.1/name/${country}`)
  .then(response => response.json())
  .then(data => renderCountry(data[0]));
};

Then I call that function, supplying a country getCountryData('czechia') to infuse it into an element like this:

const renderCountry = function(data, className = '') {
    const html = `
<article class="country ${className}">
          <img class="country__img" src="${data.flags.svg}" />
          <div class="country__data">
            <h3 class="country__name">${data.name.common}</h3>
            <h4 class="country__region">${data.region}</h4>
            <p class="country__row">${(+data.population / 1000000).toFixed(1)} people</p>
            <p class="country__row">${data.fifa}</p>
          </div>
        </article>
`
countriesContainer.insertAdjacentHTML
('beforeend', html);
countriesContainer.style.opacity = 1;
}

This works fine, but the issue is that at the end of the HTML, where I input {data.fifa} I want to have the name of the country's main currency instead. Unfortunately, the data is structured in a way, that in order to have the currency's name displayed, I first have to call it's short name, as shown below:

"currencies": {
"CZK": {
"name": "Czech koruna",
"symbol": "Kč"
}
},

If I call the {data.currencies} into the string, I'm just gonna get an empty object back. If I call it as {currencies.CZK.name}, it works, but the issue is that if I call Sweden, for example, it won't display anything, because then it'd need to be {currencies.SEK.name}. How do I get around this? How can I can call a currency's name without having to incorporate CZK, SEK, USD, EUR etc. into the variable?

Any help is appreciated.

Upvotes: 0

Views: 1431

Answers (2)

payam
payam

Reputation: 1

data.currencies is an object.To access the name of the currency in this case, you can use the Object.values() method to get an array of the values of the object, and then access the name property of the first element in that array

 const currency = Object.values(data.currencies)[0].name;

 <p class="country__row">${currency}</p>

Upvotes: 0

Elson Ramos
Elson Ramos

Reputation: 820

You can transform that object into an array:

const currencyArray = Object.values(data.currencies)
console.log(currencyArray[0].name)

If the country has many currencies, just change the index from 0 to 1, 2, ...

Upvotes: 1

Related Questions