【问题标题】:Restcountries API - getting names of currencies dynamically into HTML through JavascriptRestcountries API - 通过 Javascript 将货币名称动态转换为 HTML
【发布时间】:2021-12-07 17:32:09
【问题描述】:

我是 Javascript 新手,我一直在学习如何将国家/地区的属性导入 HTML 元素。你们中的一些人可能会认出这段代码,它来自一个教程,现在已经过时了。我一直在寻找更新的解决方案,但找不到任何解决方案。

首先我有获取数据的功能:

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

然后我调用该函数,提供一个国家 getCountryData('czechia') 将其注入到这样的元素中:

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;
}

这很好用,但问题是在 HTML 的末尾,我输入 {data.fifa} 我想改用国家主要货币的名称。不幸的是,数据的结构方式是,为了显示货币的名称,我首先必须调用它的简称,如下所示:

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

如果我将 {data.currencies} 调用到字符串中,我只会得到一个空对象。如果我称它为 {currencies.CZK.name},它可以工作,但问题是,如果我打电话给瑞典,例如,它不会显示任何内容,因为它需要是 {currencies.SEK.name }。我该如何解决这个问题?如何在不必将 CZK、SEK、USD、EUR 等合并到变量中的情况下调用货币名称?

感谢任何帮助。

【问题讨论】:

    标签: javascript html api


    【解决方案1】:

    您可以将该对象转换为数组:

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

    如果国家有多种货币,只需将索引从 0 更改为 1、2、...

    【讨论】:

    • 天哪,成功了!感谢您成为第一个在这个网站上帮助我的人^_^
    • 你可以点赞我的回答来帮助别人。
    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 2013-11-15
    • 2020-10-05
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多