ytsejam
ytsejam

Reputation: 3439

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

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>

Upvotes: 1

Views: 149

Answers (4)

Michael J. Zoidl
Michael J. Zoidl

Reputation: 1788

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

Upvotes: 2

Daniel Manta
Daniel Manta

Reputation: 6718

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

Upvotes: 0

Adam Jenkins
Adam Jenkins

Reputation: 55792

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

Upvotes: 2

krisph
krisph

Reputation: 697

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

Upvotes: 1

Related Questions