ytsejam ytsejam - 5 months ago 5
Javascript Question

How to iterate through an object?

I am trying to iterate through an object. The JSON view in the browser looks like this:

{
postalcodes: [{
adminCode2: "708",
adminCode3: "70805",
adminName3: "Breitenwang",
adminCode1: "07",
adminName2: "Politischer Bezirk Reutte",
lng: 10.7333333,
countryCode: "AT",
postalcode: "6600",
adminName1: "Tirol",
placeName: "Breitenwang",
lat: 47.4833333
}, {
adminCode2: "708",
adminCode3: "70806",
adminName3: "Ehenbichl",
adminCode1: "07",
adminName2: "Politischer Bezirk Reutte",
lng: 10.7,
countryCode: "AT",
postalcode: "6600",
adminName1: "Tirol",
placeName: "Ehenbichl",
lat: 47.4666667
}, ]
}


Until now I used forEach method:

$(document).ready(function(){
$.getJSON( "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo", function(data) {
$.each(data, function(key, val){
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
});


In the dev tools I see console message:

["<li id='0'>[object Object]</li>", "<li id='1'>[object Object]</li>",]


Actually I wanted to have all the key values as nested list elements. How can I correct my jQuery code to get this?

Thank You

Answer

value is an object that contains a postalcodes property. Subsequent to this, val, inside the loop`, is an object that contains properties. You want to do something like this:

$.each(value.postalcodes,function(key,val) {
  //val is now an object with properties adminCode2, adminCode3, etc
  //e.g. items.push("<li id='"+key+"'>"+val.postalcode+"</li>");
});