如何在Ajax期间迭代嵌套的JSON?

时间:2017-01-25 21:57:21

标签: javascript json ajax

我有这个JSON:

{
  "draw": 0,
  "recordsTotal": 90,
  "recordsFiltered": 41,
  "data": [
    {
      "id": "5",
      "art": "default/def2.jpg",
      "full_name": " ",
      "title": "Hellberg - The Girl | Atomik Remix",
      "tag": "music",
      "time": "2015-11-14",
      "": ""
    },
    {
      "id": "8",
      "art": "default/def2.jpg",
      "full_name": "Simon Deoro",
      "title": "Tim McMorris-On (Single)",
      "tag": "dance,popular,",
      "time": "2015-11-14",
      "": ""
    },
    ...
   ]
}

我想要返回id内的所有data,所以我尝试了这个功能:

function getPlaylist(id) {
    $.ajax({
        type: "GET",
        url: baseUrl+"/playlist.php?id="+id,
        cache: false,
        success: function(result) {
            var samples = JSON.parse( result );
            for (i in samples)
            {
              console.log(samples.data[i].id + "<br />");
            }
        }
    });
}

但是我从控制台

看到了这个错误
  

未捕获的TypeError:无法读取属性&#39; id&#39;未定义的

我还尝试了这个for循环(来自控制台的语法错误)

for(var i = 0; i < samples.data.length; i++)
{
    var product = samples.data[i];
    var productId = product.id;
    console.log(productId);
}

我想要的只是输出5, 8(我的id&#39; s)

我对JSON不太熟悉,那么如何才能正确访问和迭代我的结构呢?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用map函数将数组转换为另一个数组。

 var dataJSON = {
      "draw": 0,
      "recordsTotal": 90,
      "recordsFiltered": 41,
      "data": [
        {
          "id": "5",
          "art": "default/def2.jpg",
          "full_name": " ",
          "title": "Hellberg - The Girl | Atomik Remix",
          "tag": "music",
          "time": "2015-11-14",
          "": ""
        },
        {
          "id": "8",
          "art": "default/def2.jpg",
          "full_name": "Simon Deoro",
          "title": "Tim McMorris-On (Single)",
          "tag": "dance,popular,",
          "time": "2015-11-14",
          "": ""
        },
        
       ]
    };
        

var obj = dataJSON.data.map((currentValue) => currentValue.id);
console.log(obj);
在ajax函数中,您可以替换像

这样的代码
function getPlaylist(id) {
    $.ajax({
        type: "GET",
        url: baseUrl+"/playlist.php?id="+id,
        cache: false,
        success: function(result) {
            var samples = JSON.parse( result );
            var idArray = samples.data.map(x => x.id);
            console.log(idArray);
        }
    });

答案 1 :(得分:1)

samples需要samples.data

function getPlaylist(id) {
    $.ajax({
        type: "GET",
        url: baseUrl+"/playlist.php?id="+id,
        cache: false,
        success: function(result) {
            var samples = JSON.parse( result );
            for (i in samples.data)
            {
              console.log(samples.data[i].id + "<br />");
            }
        }
    });
}