You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何像访问数组一样访问Object属性?动态获取货币名称最佳方案

解决方案

你遇到的问题核心是data.currencies是键为动态货币代码的对象结构,并非数组,因此无法用索引访问,也不能写死EUR这类固定键名。
你不需要额外维护全局数组、手动清空变量,直接在renderCountry函数内使用Object.values()提取对象值即可,临时变量会在函数执行完后自动回收,无额外负担。

核心修改逻辑

  • 使用Object.values(data.currencies)将currencies对象的所有值转为数组,直接取第一个元素的name属性即可(绝大多数国家仅有一种货币,多货币场景可以拼接显示)
  • 你当前代码里的data.languages.lit也是硬编码的立陶宛语键,换成其他国家会失效,用相同方法处理即可

修改后的完整代码

const renderCountry = function (data) {
  // 动态获取货币名称
  const currencyList = Object.values(data.currencies);
  const currencyName = currencyList[0].name;
  // 多货币场景替换为下方写法:
  // const currencyName = currencyList.map(item => item.name).join('、');

  // 动态获取语言名称,解决硬编码lit失效问题
  const languageList = Object.values(data.languages);
  const languageName = languageList[0];
  // 多语言场景替换为下方写法:
  // const languageName = languageList.join('、');

  const html = ` <article class="country">
    <img class="country__img" src="${data.flags.png}" />
    <div class="country__data">
      <h3 class="country__name">${data.altSpellings[2]}</h3>
      <h4 class="country__region">${data.region}</h4>
      <p class="country__row"><span>👫</span>${(
        +data.population / 1000000
      ).toFixed(1)}</p>
      <p class="country__row"><span>🗣️</span>${languageName}</p>
      <p class="country__row"><span>💰</span>${currencyName}</p>
    </div>
  </article>`;
  countriesContainer.insertAdjacentHTML('beforeend', html);
  countriesContainer.style.opacity = 1;
};
//AJAX CALL NR1
const getCountryAndNeighbour = function (country) {
  const request = new XMLHttpRequest();
  request.open('GET', `https://restcountries.com/v3.1/name/${country}`);
  request.send();
  request.addEventListener('load', function () {
    const [data] = JSON.parse(this.responseText);
    console.log(data);
    //Render country 1
    renderCountry(data);

    //Get Neighbour Country
    const [neighbour] = data.borders;
    console.log(neighbour);
    if (!neighbour) return;
    // AJax call 2
    const request2 = new XMLHttpRequest();
    request2.open('GET', `https://restcountries.com/v3.1/alpha/${neighbour}`);
    request2.send();
    request2.addEventListener('load', function () {
      const [data2] = JSON.parse(this.responseText);
      console.log(data2);
      renderCountry(data2);
    });
  });
};
getCountryAndNeighbour('Lithuania');

内容的提问来源于stack exchange,提问作者Paul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 01:15:03