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?
asked Aug 18, 2016 at 2:54
Anson Aştepta
1,1432 gold badges14 silver badges39 bronze badges
1 Answer 1
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:
- Any time you find yourself defining variables with numeric suffixes, they should probably be an array.
- When you don't know how many of something you're going to have, put them in an array.
answered Aug 18, 2016 at 2:58
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
forloops 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++)