Im parsing a json object and storing the values I want in an array, I then push each array into a second array inside the for loop to create an array where each element in a2
is a1
.
Im already getting and parsing the json correctly.
var a1 = [];
var a2 = [];
for(i = 0; i < json.results.query.length; i++) {
var date = json.results.query[i].Date;
var name = json.results.query[i].Name;
a1[0] = date;
a1[1] = name;
console.log(a1);
a2.push(a1);
}
console.log(a2);
console.log(a1)
prints the correct array, which changes for each iteration of the for loop. For example:
["2014-01-01", "John"]
["2014-01-02", "Ann"]
["2014-01-03", "Mike"]
But console.log(a2)
prints the a2
array with the last a1
values for every index:
[["2014-01-03", "Mike"],
["2014-01-03", "Mike"],
["2014-01-03", "Mike"]]
I also tried assigning a1
to each index of a2
inside the for loop instead of using .push()
such as:
a2[i] = a1;
I want the nested (or 2-d) array, but why is each element the same?
What is going on here? Is there some javascript scoping rule? This works in other languages. Thanks!