am using API which allows me to collect data about countries. If i want get data about languages and currencies from different countries there is a problem because for example currencies in Poland has
currencies: PLN: {name: 'Polish złoty', symbol: 'zł'}
and for Portuguesa has
EUR: {name: 'Euro', symbol: '€'}.
How can i get data about currencies by code below no matter to countries? (In code i have written 'THERE IS A PROBLEM WITH CURRENCIES' this are places which i have repair.)
const btn = document.querySelector('.btn-country');
const countriesContainer = document.querySelector('.countries');
///////////////////////////////////////
const getCountryData = function (country) {
const request = new XMLHttpRequest();
request.open(
'GET',
`https://restcountries.com/v3.1/name/${country}?fullText=true`
);
request.send();
request.addEventListener('load', function () {
console.log(this.responseText);
const [data] = JSON.parse(this.responseText);
console.log(data);
const html = `
<article class="country">
<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"><span>👫</span>${(
+data.population / 1000000
).toFixed(1)} people</p>
<p class="country__row"><span>🗣️</span>${
THERE IS A PROBLEM WITH LANGUAGE
}</p>
<p class="country__row"><span>💰</span>${THERE IS A PROBLEM WITH CURRENCIES}</p>
</div>
</article>
`;
countriesContainer.insertAdjacentHTML('beforeEnd', html);
countriesContainer.style.opacity = 1;
});
};
getCountryData('portugal');
getCountryData('poland');
You have to do pretty hacky things to achieve this. I've come with this way, if you want to extract it directly from the API response:
const currencyName = data[0].currencies[Object.keys(data[0].currencies)[0]].name;
A bit more readable:
const currencies = data[0].currencies;
const currenciesKeys = Object.keys(currencies);
const currencyName = currencies[currenciesKeys[0]].name;
We're getting the first object of the array received and access the currencies key. Then, we get the subkeys of currencies as an array and access the first one, and we retrieve the name key over it.