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

如何在JSX中获取多层嵌套对象中的国家本土名称?

问题:如何在JSX中获取国家API返回的本土名称?

我想从国家API中展示选中国家的本土名称,控制台里获取该名称的路径类似:

console.log(country.name.nativeName.???.common)

其中country是选中的国家props(比如安道尔),???是对应国家的语言代码(比如cat),不同国家代码不一样。

在普通JavaScript里,我可以这样获取:

Object.values(data[i].name.nativeName)[0].common;

但在JSX里,不管怎么写console.log(Object.values(country.name.nativeName));或者它的变体,都会报“无法读取nativeName属性”的错误。

执行console.log(Object.values(country));返回:

0: 
common:"Andorra"
nativeName:cat:{official: "Principat d'Andorra", common: 'Andorra'}

补充完整的country对象:

{
    "name": {
        "common": "Andorra",
        "official": "Principality of Andorra",
        "nativeName": {
            "cat": {
                "official": "Principat d'Andorra",
                "common": "Andorra"
            }
        }
    },
    "tld": [
        ".ad"
    ],
    "cca2": "AD",
    "ccn3": "020",
    "cca3": "AND",
    "cioc": "AND",
    "independent": true,
    "status": "officially-assigned",
    "unMember": true,
    "currencies": {
        "EUR": {
            "name": "Euro",
            "symbol": "€"
        }
    },
    "idd": {
        "root": "+3",
        "suffixes": [
            "76"
        ]
    },
    "capital": [
        "Andorra la Vella"
    ],
    "altSpellings": [
        "AD",
        "Principality of Andorra",
        "Principat d'Andorra"
    ],
    "region": "Europe",
    "subregion": "Southern Europe",
    "languages": {
        "cat": "Catalan"
    },
    "translations": {
        "ara": {
            "official": "إمارة أندورا",
            "common": "أندورا"
        },
        "bre": {
            "official": "Priñselezh Andorra",
            "common": "Andorra"
        },
        "ces": {
            "official": "Andorrské knížectví",
            "common": "Andorra"
        },
        "cym": {
            "official": "Tywysogaeth Andorra",
            "common": "Andorra"
        },
        "deu": {
            "official": "Fürstentum Andorra",
            "common": "Andorra"
        },
        "est": {
            "official": "Andorra Vürstiriik",
            "common": "Andorra"
        },
        "fin": {
            "official": "Andorran ruhtinaskunta",
            "common": "Andorra"
        },
        "fra": {
            "official": "Principauté d'Andorre",
            "common": "Andorre"
        },
        "hrv": {
            "official": "Kneževina Andora",
            "common": "Andora"
        },
        "hun": {
            "official": "Andorra",
            "common": "Andorra"
        },
        "ita": {
            "official": "Principato di Andorra",
            "common": "Andorra"
        },
        "jpn": {
            "official": "アンドラ公国",
            "common": "アンドラ"
        },
        "kor": {
            "official": "안도라 공국",
            "common": "안도라"
        },
        "nld": {
            "official": "Prinsdom Andorra",
            "common": "Andorra"
        },
        "per": {
            "official": "شاهزاده‌نشین آندورا",
            "common": "آندورا"
        },
        "pol": {
            "official": "Księstwo Andory",
            "common": "Andora"
        },
        "por": {
            "official": "Principado de Andorra",
            "common": "Andorra"
        },
        "rus": {
            "official": "Княжество Андорра",
            "common": "Андорра"
        },
        "slk": {
            "official": "Andorrské kniežatstvo",
            "common": "Andorra"
        },
        "spa": {
            "official": "Principado de Andorra",
            "common": "Andorra"
        },
        "srp": {
            "official": "Кнежевина Андора",
            "common": "Андора"
        },
        "swe": {
            "official": "Furstendömet Andorra",
            "common": "Andorra"
        },
        "tur": {
            "official": "Andorra Prensliği",
            "common": "Andorra"
        },
        "urd": {
            "official": "اماراتِ انڈورا",
            "common": "انڈورا"
        },
        "zho": {
            "official": "安道尔公国",
            "common": "安道尔"
        }
    },
    "latlng": [
        42.5,
        1.5
    ],
    "landlocked": true,
    "borders": [
        "FRA",
        "ESP"
    ],
    "area": 468,
    "demonyms": {
        "eng": {
            "f": "Andorran",
            "m": "Andorran"
        },
        "fra": {
            "f": "Andorrane",
            "m": "Andorran"
        }
    },
    "flag": "🇦🇩",
    "maps": {
        "googleMaps": "https://goo.gl/maps/JqAnacWE2qEznKgw7",
        "openStreetMaps": "https://www.openstreetmap.org/relation/9407"
    },
    "population": 77265,
    "fifa": "AND",
    "car": {
        "signs": [
            "AND"
        ],
        "side": "right"
    },
    "timezones": [
        "UTC+01:00"
    ],
    "continents": [
        "Europe"
    ],
    "flags": {
        "png": "https://flagcdn.com/w320/ad.png",
        "svg": "https://flagcdn.com/ad.svg",
        "alt": "The flag of Andorra features three equal vertical bands of blue, yellow and red, with the coat of arms of Andorra centered in the yellow band."
    },
    "coatOfArms": {
        "png": "https://mainfacts.com/media/images/coats_of_arms/ad.png",
        "svg": "https://mainfacts.com/media/images/coats_of_arms/ad.svg"
    },
    "startOfWeek": "monday",
    "capitalInfo": {
        "latlng": [
            42.5,
            1.52
        ]
    },
    "postalCode": {
        "format": "AD###",
        "regex": "^(?:AD)*(\\d{3})$"
    }
}

解决方案

核心原因

报错本质是组件渲染初期country或country.name未初始化——JSX会在组件的每一次渲染周期执行代码,包括API请求还未返回、country仍为undefined的阶段,这时直接访问country.name.nativeName就会触发空值错误。

具体实现方式

1. 可选链+空值合并(推荐)

用可选链操作符?.规避空值访问,配合Object.values获取第一个本土名称,再用空值合并??设置兜底值:

// 直接在JSX中嵌入
{country?.name?.nativeName 
  ? Object.values(country.name.nativeName)[0].common 
  : country?.name?.common ?? '未知国家'}

// 提取为变量更清晰
const nativeCommonName = country?.name?.nativeName 
  ? Object.values(country.name.nativeName)[0].common 
  : country?.name?.common;

// 渲染到页面
{nativeCommonName}

2. 传统条件判断(兼容旧环境)

如果项目不支持可选链语法,用多层条件判断包裹:

{country && country.name && country.name.nativeName && 
  Object.values(country.name.nativeName)[0].common
}

3. 利用languages字段精准匹配

从完整country对象可以看到,languages的key和nativeName的key完全一致(比如安道尔的cat),可以通过这个字段直接获取对应语言的本土名称:

const firstLangCode = country?.languages && Object.keys(country.languages)[0];
const nativeCommonName = firstLangCode 
  ? country.name.nativeName[firstLangCode].common 
  : country?.name?.common;

{nativeCommonName}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:01:03