This is my json response
{"COLUMNS":["LABEL1", "LABEL2", "RATE1", "RATE2"], "DATA":[["tps", "tvq", 10.0, 20.0]]}
And I want to be able to loop only over the DATA element.
I don't have any code because I have no clue how to do this. Just learning this new language.
3 Answers 3
// response.DATA is an array with just one element
var dataElements = response.DATA;
// The first element in that array is another array containing your data
var firstData = dataElements[0];
// Loop through and access each individual element
for (var i = 0; i < firstData.length; i++) {
alert(firstData[i]);
}
answered Jul 15, 2011 at 16:35
Raul Agrait
6,0386 gold badges51 silver badges72 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
for(var i in response.DATA){
alert(response.DATA[i];
}
answered Jul 15, 2011 at 16:34
DrStrangeLove
11.6k16 gold badges63 silver badges73 bronze badges
Comments
If there are only arrays inside the DATA and you need each array, then do it like this:
for(var i in response.DATA){
alert(response.DATA[i]);
}
Otherwise if you want all the values tps, tvq, 10.0, and 20.0, then do it like this:
for(var i in response.DATA[0]){
alert(response.DATA[0][i]);
}
Update
var arrData = response.DATA[0],
sizeOfData = arrData.length,
i = 0;
for(i; i < sizeOfData; i++){
alert(arrData[i]);
}
answered Jul 15, 2011 at 16:30
Shef
45.7k15 gold badges82 silver badges91 bronze badges
3 Comments
lonesomeday
That won't work usefully (since
DATA[0] is the only element in DATA and is an array itself) and it's not good to loop through arrays with for..in loops.Shef
@lonesomeday: I had edited already. Any benchmarks on the speed between
for .. in and for, please enlighten me.lonesomeday
Speed isn't the isssue. Things like
Array.prototype.forEach = function(){} are the problem. for..in should be used for looping over object properties; for for array elements.lang-js