user4819461
user4819461

Reputation:

Looping through a nested JSON object

So I've gotten a list of airports in a JSON format, and it's like this:

Below are a few entries from the array:

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"
}
}

Each of the 00AK, 00AL, 00AZ, etc. objects represents a certain airport. Now what I want to do is get the attributes of each of these objects.

Here's what I've tried to do for getting the "name" attribute:

for (var airport in airportData)
{
    var opt = document.createElement("option");
    opt.innerHTML = airport.name + " (" + airport.icao + ")";
    airport_list.appendChild(opt);
    console.log(airport.name);
}

But airport.name always returns "undefined". I've looked at numerous other examples but they all have a different structure than then one I'm looking at.

So my question is, what should I change in my code to get the "name" attribute?

Upvotes: 1

Views: 33

Answers (1)

Lionel Damtew
Lionel Damtew

Reputation: 38

In the foor loop, the variable airport will loop through the keys of airportData. If you want to loop through the values you need to access them via airportData[airport]. An improved version of your code would look like this:

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

Upvotes: 0

Related Questions