1

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>
ytsejam
  • 3,291
  • 7
  • 39
  • 69

4 Answers4

2

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>");
});
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Adam that did the job , but I had to mix with krisph's answer , I am close but I cant append it to html. can you check my edited code. I want ot place it in the body. – ytsejam Jul 06 '16 at 13:56
2

You want go through the postalcodes array, right? Because it's an array - not an object.

If yes, you could loop easy with an map function

postalcodes.map(function(postal) {
  // now the "postal" is the object which contains the single props 
});

In your case - if you stay with this jQuery stuff - use the response from the API, take the postalcodes array and map them .. return the results and save them in the items var..

$(document).ready(function(){
    $.getJSON( "http://api...", function(data) {
        var items = data.postalcodes.map(function(postal, id) {
          return '<li id="' + id + '">' + postal.adminName2 +  '</li>';
        })
    });
});

And if you use EcmaScript 6

$(document).ready(() =>{
    $.getJSON( "http://api...", (data) => {
        var items = data.postalcodes.map((postal, id) => '<li id="' + id + '">' + postal.adminName2 +  '</li>');
    });
});

Hope i can help...

EDIT

Just a FYI, in ES6 you could write it a way shorter :)

$(document).ready(() =>{
    $.getJSON( "http://api...", ({postalcodes:zips}) => {
        const items = zips.map(({adminName2:name}, id) => `<li id="${id}">${name}</li>`);
    });
});
Michael J. Zoidl
  • 1,708
  • 16
  • 13
1

haven't tested but somthing like this?

for (var prop in value) {
 for (var prop2 in value[prop]) {
  items.push( "<li id='" + prop2 + "'>" + value[prop][prop2] + "</li>" );
 }
}
krisph
  • 639
  • 1
  • 10
  • 14
  • It's best not to use a `for..in` loop on an array for the outer loop. See [this question](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea). A normal `for` loop is safest. – 4castle Jul 06 '16 at 13:40
0

The api is not available at the moment but I've got some data I previously saved.

var data = {'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':'6610', 'adminName1':'Tirol', 'placeName':'Ehenbichl','lat': '47.4666667'}]};

First of all you need to iterate through postalcodes and then for each object get the value of postalcode.

var items = [];
$.each(data.postalcodes, function () {
    items.push("<li id='postalcode'>" + this.postalcode + "</li>");
});
console.log(items);

Output is:

["<li id='postalcode'>6600</li>", "<li id='postalcode'>6610</li>"]
derloopkat
  • 6,232
  • 16
  • 38
  • 45