Zach_is_my_name Zach_is_my_name - 1 month ago 8
Javascript Question

assign multiple values to object property with for loop

I'm trying to assign the

name
property of
obj
the
[i][0]
indices of
sampleArr
.
Console.log(arr[i][0])
outputs
"animals", "sopranos", "guitars"
with each iteration. However, obj.name = arr[i][0] will only assign
obj.name = "guitars"
.
What explains this behavior, and how could I assign these multiple elements to a single property within a loop?

var sampleArr = [
["animals", ["dogs", "cats", "pigs"]],
["sopranos", ["Tony", "Carmella", "AJ", "Meadow"]],
["guitars", ["Stratocaster", "Telecaster", "Gibson Flying-V"]]
];


function objectifier(arr) {
var obj = {};
for (var i = 0; i < arr.length; i++) {
console.log(arr[i][0])
obj.name = arr[i][0]
}
return obj;
}

Answer

Replace

obj.name = arr[i][0] 

with

obj[i] = {};
obj[i]["name"] = arr[i][0];
Comments