循环嵌套的JSON对象

问题描述 投票:1回答:1

所以我得到了一个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等对象中的每一个代表某个机场。现在我想要做的是获取每个对象的属性。

这是我为获取“name”属性而尝试做的事情:

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总是返回“undefined”。我看了很多其他的例子,但它们都有不同于我正在看的结构。

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

json nested
1个回答
1
投票

在foor循环中,变量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);
}
© www.soinside.com 2019 - 2024. All rights reserved.