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

如何无需指定父键,直接获取API嵌套对象中的目标属性值?

动态获取API对象中不确定父键的嵌套值

我从API拿到的对象结构如下:

{
  "name": {
    "common": "Germany",
    "official": "Federal Republic of Germany",
    "nativeName": {
      "deu": {
        "official": "Bundesrepublik Deutschland",
        "common": "Deutschland"
      }
    }
  },
  "currencies": {
    "EUR": {
      "name": "Euro",
      "symbol": "€"
    }
  }
}

我需要获取nativeName下的common值(比如例子里的"Deutschland")和currencies下的name值(比如例子里的"Euro"),但不同国家数据里,deu、EUR这类父键是动态变化的,没法写死。有没有办法不用硬编码这些键就能拿到目标值?


当然可以,用JavaScript的对象遍历方法就能搞定,核心是先拿到动态键对应的子对象,再取目标属性:

1. 获取nativeName下的common值

nativeName里通常只会有一个主语言对应的键,直接用Object.values()取出它的子对象,再取common即可:

// 假设apiData是你拿到的完整API返回对象
const nativeCommon = Object.values(apiData.name.nativeName)[0].common;
// 例子中会得到 "Deutschland"

如果遇到存在多语言条目的极端情况,也可以遍历所有值取第一个符合条件的结果,不过这类国家API的nativeName一般只会保留官方主语言的条目。

2. 获取currencies下的name值

和上面的逻辑一致,currencies里的货币键是动态的,同样用Object.values()处理:

const currencyName = Object.values(apiData.currencies)[0].name;
// 例子中会得到 "Euro"

如果某个国家有多种货币,想要获取所有货币名称,可以改成遍历数组:

const allCurrencyNames = Object.values(apiData.currencies).map(curr => curr.name);
// 得到包含所有货币名称的数组

你也可以用Object.keys()先拿到动态键的名称,再通过键取值,效果完全相同:

// 拿nativeName的common值
const langKey = Object.keys(apiData.name.nativeName)[0];
const nativeCommon = apiData.name.nativeName[langKey].common;

// 拿currencies的name值
const currKey = Object.keys(apiData.currencies)[0];
const currencyName = apiData.currencies[currKey].name;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 01:36:24