简体   繁体   中英

How do I iterate over a nested JSON during Ajax?

I have this 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",
      "": ""
    },
    ...
   ]
}

I want to return all id 's inside data , so I tried this function:

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

however I see this error from console

Uncaught TypeError: Cannot read property 'id' of undefined

I tried also this for loop (syntax error from console)

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

All I want is output 5, 8 (my id 's)

I'm not very familiar with JSON, so how can I access and iterate over my structure correctly?

You can try using the map function to transform the array to another array.

  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); 
In the ajax function, you can replace the code like this

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

samples needs to be 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 />");
            }
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM