Looping through a json array of objects

I have been trying to follow an example as per another stackoverflow question:

javascript or jquery: Looping a multidimensional object

I am posting this question as a last resort as I have been on the problem for hours!

I have an ajax function that returns a json array.

ajax:

  $.ajax({ url: 'functions.php',
           data: {action: 'getNFCMapping', site: site_id},
           type: 'post',
           dataType: 'json',
           success: function(data) {
            //loop the json to get the
                for (var key in data) {
                      console.log(data[key].nfc_id);
                  }
            } //end success
  });//end ajax

json array:

[{"24":{"nfc_id":"1","description":"sdfgdsg"}},{"25":{"nfc_id":"2","description":"dfgdfgdfg"}},{"26":{"nfc_id":"3","description":"fdgdffg"}},{"27":{"nfc_id":"4","description":"dfgdfgdfg"}}]

What I am trying to do eventually is load a form in the DOM with input fields (pre-populated) in pairs of nfc_id and description, therefore each iteration of the loop should output the two values.

The problem at the moment is that I can't actually access the values in each iteration, e.g. you can see I am trying to log the nfc_id of each iteration but it just appears as object in the console.

In the example ( javascript or jquery: Looping a multidimensional object ), I can see the difference in format of my json, in that I have two closing brackets on each iteration of my array, is this what the issue is?

Please help this is driving me crazy..

Answers


You want two nested .each() loops:

$.each(data, function(key, value) {
    $.each(value, function(k, v) {
       console.log(v.nfc_id); 
    });
});

Fiddle


You data is an array, so you should use for (var i = 0; i < data.length; i++) loop. Each element is an object so you use var key in obj notation:

for (var i = 0; i < data.length; i++) {
    for (var key in data[i]) {
        console.log(data[i][key].nfc_id);
    }
}

Perhaps try the .each jQuery method? Link

So for your success:

success: function(data){
    $(data).each(function(index, element){
      //log here
    }
}

for(var i=0, i<data.length;i++)
$.each(data[i], function(key, val) {
    console.log(val.nfc_id);
    console.log(val.description);
});

Need Your Help

Carrierwave custom headers on local files

ruby-on-rails ruby-on-rails-3 carrierwave

I'd like to send all files from a certain uploader with custom headers (specifically, the content-disposition header). My files are NOT stored on Fog / S3, they're stored locally.