【问题标题】:Looping through json with multiple arrays使用多个数组循环遍历 json
【发布时间】:2016-11-25 13:50:00
【问题描述】:

我正在使用 json 和 jQuery 从 Instagram 中提取图片。

json 数据包含对象和数组。不知何故,我无法将第二个数组循环到我需要的值。

这是我的代码:

var request = "./myapi.php?user=jamieoliver"; //&callback=myFunction
$.ajax({
  cache: false,
  dataType: "json", // or "jsonp" if we enabled it
  url: request,
  success: function(response) {
    console.log(response);
    for (var i = 0; i < response.entry_data.ProfilePage.length; i++) {
      console.log(response.entry_data.ProfilePage[i].user.media.nodes[i].thumbnail_src);
    }
  },
  error: function(xhr, status, error) {}
});

问题出现在这里:nodes[i] - nodes[] 是一个数组 - 我的代码没有循环遍历它 - 它只给了我在 nodes[] 内的第一个对象内的值。如何循环遍历节点 [] 以便在其每个对象中获取 thumbnail_src 的值?

我没有实时数据,但这里是 json 响应结构的屏幕截图:

【问题讨论】:

  • 如果可以,请始终发布代码而不是图片。
  • 我宁愿说更好的选择是对对象使用高级或 for 循环。

标签: jquery arrays json


【解决方案1】:

类似这样的:

var request = "./myapi.php?user=jamieoliver"; //&callback=myFunction
$.ajax({
  cache: false,
  dataType: "json", // or "jsonp" if we enabled it
  url: request,
  success: function(response) {
    console.log(response);
    for (var i = 0; i < response.entry_data.ProfilePage.length; i++) {
        for (var j = 0; j < response.entry_data.ProfilePage[i].user.media.nodes.length; j++) {
          console.log(response.entry_data.ProfilePage[i].user.media.nodes[j].thumbnail_src);
       }
    }
  },
  error: function(xhr, status, error) {}
});

【讨论】:

    【解决方案2】:

    您应该使用另一个 for 再次循环:

    var request = "./myapi.php?user=jamieoliver"; //&callback=myFunction
    $.ajax({
      cache: false,
      dataType: "json", // or "jsonp" if we enabled it
      url: request,
      success: function(response) {
        console.log(response);
        var nodes;
        for (var i = 0; i < response.entry_data.ProfilePage.length; i++) {
          nodes = response.entry_data.ProfilePage[i].user.media.nodes;
    
          for (var n = 0; n < nodes.length; n++) { 
            console.log(nodes[n].thumbnail_src);
          }
        }
      },
      error: function(xhr, status, error) {}
    });
    

    【讨论】:

    • 该死,我回答的时间太长了。好吧,我建议使用var nodes; 以更简洁的方式循环第二个for,以便您可以更快地阅读和理解它。
    • 这个也很有用。但是是否有可能创建某种函数来自动循环它遇到的每个数组?我的意思是,这样我们就不必使用多个 for 循环了吗?
    • @Meek 这是个好问题。我已经在 PHP 中做到了,但它必须在 javascript 中类似。您必须创建一个函数来循环它找到的每个数组/对象,然后如果它找到另一个数组/对象,则在其内部运行该函数。但是我想不出我们怎么能使用它,因为在你的例子中你正在寻找一个特定的对象entry_data.ProfilePage[i].user.media.nodes
    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多