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

如何使用JavaScript获取JSON二级子字段production_countries的name值

实现方式

你的示例中production_countries是数组类型,数组的第一个元素(下标为0)存储了包含name字段的对象,直接按「属性访问+数组下标访问+属性访问」的顺序取值即可。如果存在多个国家,可遍历数组依次获取每个元素的name属性。

基础写法(确定数组非空时使用)

// 直接获取name字段值
const countryName = out.production_countries[0].name;
// 渲染到页面示例(假设对应DOM节点id为production_country)
let countryEle = document.getElementById("production_country");
countryEle.innerHTML = countryName;

兼容异常场景的写法

如果不能保证production_countries一定存在、或者数组至少有一个元素,建议加判断逻辑避免运行报错:

// ES2020+ 可选链写法,异常场景下返回undefined,不会抛出错误
const countryName = out.production_countries?.[0]?.name;

// 兼容旧JS环境的写法,数组为空/不存在时返回空字符串
const countryName = out.production_countries && out.production_countries.length ? out.production_countries[0].name : '';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:39:03