Question:
Why does the declaration of the obj variable have to move to the "//MOVE TO HERE" location below to properly produce an array of both the {number: 1, color: blue} and {number: 2, color: red} objects? When the declaration stays in its current spot below, the array results in {number: 2, color: red}, {number: 2, color: red} (i.e. the same object, twice)
My understanding:
In its current position, the arrObj array is updated with the most current value of obj, so the output is an array that twice lists "number: 2, color: red".
Confusion:
How come both objects appear in the array when the obj declaration is moved to //MOVE TO HERE below? If the array is dynamically updated with each update of obj, why is arrObj[0] not cleared and then updated with the new values of obj when obj is declared a second time?
function arrayOfObjects(array) {
var arrObj = [];
var obj = {};
for (i = 0; i < array.length; i++) {
//MOVE TO HERE
for (j = 0; j < array[i].length; j++) {
obj[array[i][j][0]] = array[i][j][1];
}
arrObj[i] = obj;
}
return arrObj;
}
var array = [ [ ['number', '1'], ['color', 'blue'] ] , ['number', '2'], ['color', 'red'] ] ]
arrayOfObjects(array);