tags:

views:

6118

answers:

3

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

How can I loop over the results so that I would have access to each of the elements? I have tried something like below but this does not seem to be working.

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});
+3  A: 

You were close:

$.each(data, function() {
  $.each(this, function(k, v) {
    /// do stuff
  });
});

You have an array of objects/maps so the outer loop loops through those. The inner loop loops through the properties on each object element.

cletus
Why double looping?
Asaf
The first loop is for a "category" while a loop within that is for an "attribute." How else is that done?
dcolumbus
A: 

Access the json array like you would any other array.

for(var i =0;i<itemData.length-1;i++) { var item = itemData[i]; alert(item.Test1 + item.Test2 + item.Test3); }

A: 

if you use FF, just open up a console and try out this:

var a = [
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];

$.each (a, function (bb) {
    console.log (bb);
    console.log (a[bb]);
    console.log (a[bb].TEST1);
});

hope it helps

ifesdjeen