Struggling to convert the given array into object properties using nested array notation: array[x][y]
var array = [['make', 'Ford'], ['model', 'Mustang'], ['year', 1964]];
function fromListToObject(array) {
var result = {};
for(var i = 0;i < array.length;i++){
console.log(array[i]); // checking output
for(var j = 0;j < array[i].length;j++){
console.log(array[i][j]); // checking output
console.log(array[i][j+1]); // checking output
result[array[i][j]] = array[i][j+1];
}
}
return result;
}
fromListToObject(array);
Current Output:
[ 'make', 'Ford' ] //inner array
make //key
Ford //value
Ford //unexpected
undefined
[ 'model', 'Mustang' ]
model
Mustang
Mustang
undefined
[ 'year', 1964 ]
year
1964
1964
undefined
=> { '1964': undefined, //Issue here?
make: 'Ford', //Correct!
Ford: undefined,
model: 'Mustang',
Mustang: undefined,
year: 1964 }
I did manage to solve this with forEach
:
function fromListToObject(array) {
var result = {};
array.forEach(function(element){
result[element[0]] = element[1];
});
return result;
}
and I can capture the inner array into a temporary variable too. Seeking guidance for improvement. Thanks.
EDIT
Appreciate the help provided. Learners like me need such guidance.