1

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?

2
  • maybe use a while loop that runs until you are out of data? Commented Aug 18, 2016 at 2:56
  • 1
    The double for loops are your best bet. Also, for(var i = 0; i < data.result.data.length; i++) Should be changed to: for(var i = 0; i < data.result[k].data.length; i++) Commented Aug 18, 2016 at 2:58

1 Answer 1

4

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

Comments

Your Answer

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.