json - 遍历嵌套的 JSON 对象
问题描述
所以我得到了一个 JSON 格式的机场列表,它是这样的:
以下是数组中的一些条目:
var airportData = {
"00AK": {
"icao": "00AK",
"iata": "",
"name": "Lowell Field",
"city": "Anchor Point",
"state": "Alaska",
"country": "US",
"elevation": 450,
"lat": 59.94919968,
"lon": -151.695999146,
"tz": "America\/Anchorage"
},
"00AL": {
"icao": "00AL",
"iata": "",
"name": "Epps Airpark",
"city": "Harvest",
"state": "Alabama",
"country": "US",
"elevation": 820,
"lat": 34.8647994995,
"lon": -86.7703018188,
"tz": "America\/Chicago"
},
"00AZ": {
"icao": "00AZ",
"iata": "",
"name": "Cordes Airport",
"city": "Cordes",
"state": "Arizona",
"country": "US",
"elevation": 3810,
"lat": 34.3055992126,
"lon": -112.1650009155,
"tz": "America\/Phoenix"
}
"00CA": {
"icao": "00CA",
"iata": "",
"name": "Goldstone \/Gts\/ Airport",
"city": "Barstow",
"state": "California",
"country": "US",
"elevation": 3038,
"lat": 35.3504981995,
"lon": -116.888000488,
"tz": "America\/Los_Angeles"
},
"00CO": {
"icao": "00CO",
"iata": "",
"name": "Cass Field",
"city": "Briggsdale",
"state": "Colorado",
"country": "US",
"elevation": 4830,
"lat": 40.6222000122,
"lon": -104.34400177,
"tz": "America\/Denver"
},
"00FA": {
"icao": "00FA",
"iata": "",
"name": "Grass Patch Airport",
"city": "Bushnell",
"state": "Florida",
"country": "US",
"elevation": 53,
"lat": 28.6455001831,
"lon": -82.21900177,
"tz": "America\/New_York"
}
}
00AK、00AL、00AZ 等对象中的每一个都代表一个特定的机场。现在我想做的是获取每个对象的属性。
这是我为获取“名称”属性所做的尝试:
for (var airport in airportData)
{
var opt = document.createElement("option");
opt.innerHTML = airport.name + " (" + airport.icao + ")";
airport_list.appendChild(opt);
console.log(airport.name);
}
但 airport.name 总是返回“未定义”。我查看了许多其他示例,但它们的结构都与我正在查看的不同。
所以我的问题是,我应该在我的代码中进行哪些更改以获得“名称”属性?
解决方案
在 foo 循环中,变量airport
将遍历airportData
. 如果要循环访问需要通过airportData[airport]
. 您的代码的改进版本如下所示:
for (var key in airportData)
{
var airport = airportData[key];
var opt = document.createElement("option");
opt.innerHTML = airport.name + " (" + airport.icao + ")";
airport_list.appendChild(opt);
console.log(airport.name);
}
推荐阅读
- html - 链接在 HTML 页面中的可点击框网格中不起作用
- python - 使用 Python 列表推导获取二叉树中的下一层节点
- java - 如何在 Java 中制作 10^3 位的 BigInteger?
- html - 移动 html 单选按钮文本大小随方向缩放
- javascript - 模态组件vuejs2中未显示内容(图片)
- apache - 让 Apache Substitute for multipart/mixed 工作
- hadoop - Apache Pig 查询 - 数据集连接错误 1031
- google-apps-script - 如何将电子表格的访问权限从编辑器更改为查看器?
- python - 使用 pandas 将年、月、日列组合成单个日期列
- python - 当我尝试在 Windows 10 上安装 caffe 时,脚本找不到 python 库和 numpy