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
edited answer : this is what I become now :
<script>
$(document).ready(function(){
$.getJSON( "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo", function( data ) {
var items = [];
$.each(data, function (key, value) {
$('body').append($('<div></div>').html(key + ' (' + value.length + ' results)'));
var list = $('<ul></ul>');
$('body').append(list);
});
$.each(data.postalcodes, function(key, val){
for (var k in val) {
if (val.hasOwnProperty(k)) {
items.push( "<li id='" + k + "'>" + val[k] + "</li>" );
}
}
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
});
});
</script>