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.
CodePudding user response:
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.
CodePudding user response:
you can do it more simple way
function displayCountry(data){
Object.keys(data[0].currencies).forEach(key => {
document.querySelector("#currency").innerHTML = data[0].currencies[key].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;
});
});
};
CodePudding user response:
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;
}