I want to display the name of the currency of different countries. To do this I use an API and fetch the json in my JS file.
The problem is the different names. In this case "BRL" oder "USD" to enter the names of the currencies.
In this case I used "BRL", but I want to be able to enter every different countries currency element. I would think that I would need some sort of wildcard.
Maybe some of you can help me on how to handle this problem.
I actually found out that there is an older version of the API in which the currency is display a lot simplier. That way I can access the currencies of each country easier.
In the older version the json for USA´s currency for example would look like this
That way I dont actually need to enter the different kinds of currencies first, when fetching the data.
you can do it more simple way
document.querySelector("#currency").innerHTML =
Object.values(data[0].currencies)[0].name;
or maybe this if you want to show several properties
function displayCountry(data) {
data.forEach((item) => {
Object.keys(item.currencies).forEach((key) => {
document.querySelector("#currency").innerHTML = item.currencies[key].name;
});
});
};
If you are calling the API with a currency abbreviation like "USD" and "BRL", then you can put those into an array like this:
const arrayOfCurrencies = ["USD", "BRL", ...];
When you are displaying them to the DOM, you can use those values as dynamic properties of the response like so:
for(let abbr of arrayOfCurrencies) {
document.querySelector("#currency").innerHTML = data[0].currencies?.[abbr]?.name ?? fallbackString;
}