首页 > 解决方案 > 遍历嵌套的 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 总是返回“未定义”。我查看了许多其他示例,但它们的结构都与我正在查看的不同。

所以我的问题是,我应该在我的代码中进行哪些更改以获得“名称”属性?

标签: jsonnested

解决方案


在 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);
}

推荐阅读