Flame of udun
Flame of udun

Reputation: 2237

Jquery $.each() not iterating over all objects

I am trying to iterate through all objects returned in json by an api. Here is my code :

$(document).ready(function() {
     $('.form-container').submit(function() {

          var $body = $('body');
          var $greeting = $('#greeting');

          // load streetview
          var streetname = $("#street").val();
          var cityname = $("#city").val();
          var address = streetname + ', ' + cityname;

          var bigImgUrl = "https://maps.googleapis.com/maps/api/streetview?size=600x400&location="+ address +'';

          $greeting.text("So you want to live at " + address + "?");

          $body.append('<img class="bgimg" src='+bigImgUrl+'>');

          // NYTimes AJAX request
          var nytUrl = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q="+cityname+"&sort=newest&api-key=####";

          $.getJSON(nytUrl, function(data) {

              createStructure(data); // Call to recursive function

          });
          return false;
     });

    var createStructure = function (data)
    {
        $.each(data, function(key, value) {
            if (typeof value === 'object')
            {
                 alert(key + ": " + value);
                 createStructure(data[key]);
            }
            else 
            {
                 alert(key + ": " + value);
            }
        });

    };

    return false;
});

However it doesn't iterate through all them. Here is a screenshot depicting a part of the json returned by the API :

enter image description here

The code shows alerts for only entering response, all of meta(including children ie), entering docs and the 0 object(only some children elements). It skips all the remaining children of docs and the other outer objects.

Here is the link to the json : JSON

Upvotes: 0

Views: 476

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

Use use a for in loop instead of $.each:

var createStructure = function (data) {
    for (var key in data){
        var value = data[key];
        if (typeof value === 'object') {
            console.log(key + ": " + value);
            createStructure(value);
        } else {
            console.log(key + ": " + value);
        }
    }
};

JSFiddle: http://jsfiddle.net/TrueBlueAussie/q4vuc789/1

Upvotes: 1

Related Questions