Zach_is_my_name
Zach_is_my_name

Reputation: 59

How do I 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;
}

Upvotes: 0

Views: 684

Answers (2)

theCJCsoccer
theCJCsoccer

Reputation: 621

Replace

obj.name = arr[i][0] 

with

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

Upvotes: 0

jonzee
jonzee

Reputation: 1609

how could I assign these multiple elements to a single property within a loop?

To achieve this you have to keep array in this single property, like this:

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

Upvotes: 1

Related Questions