anson920520 anson920520 - 3 months ago 7
Javascript Question

Javascript : Store data in variables by for loop

I am having some random JSON data at the moment, therefore I cannot using standrad way to do it, cannot do it one by one.

For example if i am going to store specific data as array i will do something like below

var tester = []; // store their names within a local array

for(var k = 0; i < data.result.length; i++){ //maybe 6

for(var i = 0; i < data.result.data.length; i++){ //maybe 30 times in total

tester.push(data.result[k].data[i].someNames);
}

}


But since I cannot predict how many set of data i have i can't really do something like

var tester = [];
var tester2 = [];
var tester3 = [];
var tester4 = [];

for(var i = 0; i < data.result.data.length; i++){ //maybe 30 times in total

tester.push(data.result[0].data[i].someNames);
tester2.push(data.result[1].data[i].someNames);
tester3.push(data.result[2].data[i].someNames);
tester4.push(data.result[3].data[i].someNames);


}


if there' any better way which using for loop to store these data?

Answer

Make tester a 2-dimensional array and use nested loops.

var tester = [];

for (var i = 0; i < data.result.length; i++) {
    var curTester = [];
    var result = data.result[i];
    for (var j = 0; j < result.data.length; j++) {
        curTester.push(result.data[j].someNames);
    }
    tester.push(curTester);
}

Some general principles:

  1. Any time you find yourself defining variables with numeric suffixes, they should probably be an array.
  2. When you don't know how many of something you're going to have, put them in an array.
Comments