Jquery $ .each()不迭代所有对象

时间:2015-04-08 13:31:56

标签: jquery json

我试图通过api遍历json中返回的所有对象。这是我的代码:

$(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;
});

然而,它并没有遍历所有这些。这是一个屏幕截图,描述了API返回的部分json:

enter image description here

代码会显示仅输入response,所有meta(包括子项),提交docs0对象(仅限某些子元素)的提醒。 它会跳过docs的所有剩余子项和其他外部对象。

以下是json的链接:JSON

1 个答案:

答案 0 :(得分:1)

使用for in循环代替$.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