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

React项目中如何处理Rest Countries API v3.1的动态货币与语言数据

解决Rest Countries API中动态键名的货币与语言数据访问问题

核心思路

针对languages和currencies这种键名不固定的对象,直接用JavaScript的Object.values()或Object.entries()方法提取数据,无需依赖具体键名。

1. 处理语言数据

languages对象的键是语言代码,值是语言名称,直接提取所有值即可:

// 假设已获取到国家数据data
const languages = Object.values(data.languages);
// 渲染时遍历数组
return (
  <div>
    <h3>官方语言</h3>
    <ul>
      {languages.map((lang, index) => (
        <li key={index}>{lang}</li>
      ))}
    </ul>
  </div>
);

2. 处理货币数据

currencies对象的键是货币代码,值是包含name(货币名称)和symbol(符号)的对象,可按需提取:

  • 方法一:只提取货币名称
const currencyNames = Object.values(data.currencies).map(curr => curr.name);
// 渲染
return (
  <div>
    <h3>货币</h3>
    <ul>
      {currencyNames.map((name, index) => (
        <li key={index}>{name}</li>
      ))}
    </ul>
  </div>
);
  • 方法二:同时展示货币代码、名称和符号
const currencyEntries = Object.entries(data.currencies);
// 渲染
return (
  <div>
    <h3>货币详情</h3>
    <ul>
      {currencyEntries.map(([code, curr], index) => (
        <li key={index}>
          {code}: {curr.name} ({curr.symbol})
        </li>
      ))}
    </ul>
  </div>
);

注意事项

若数据可能为空,建议添加空值判断避免报错:

const languages = data.languages ? Object.values(data.languages) : [];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:30:49