0

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.

AstroCB
12.4k20 gold badges59 silver badges76 bronze badges
asked Jul 15, 2011 at 16:29
0

3 Answers 3

2
// 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
Sign up to request clarification or add additional context in comments.

Comments

0
for(var i in response.DATA){
 alert(response.DATA[i];
}
answered Jul 15, 2011 at 16:34

Comments

0

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

3 Comments

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.
@lonesomeday: I had edited already. Any benchmarks on the speed between for .. in and for, please enlighten me.
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.