0

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;
}
6
  • What is the end result data structure that you want? Commented Oct 21, 2016 at 19:27
  • Try obj["name"] = arr[i][0] Commented Oct 21, 2016 at 19:28
  • name: "animals", "sopranos", "guitars" Commented Oct 21, 2016 at 19:29
  • So you should use obj.name = [] and then obj.name.push(arr[i][0]) Commented Oct 21, 2016 at 19:30
  • @nurdyguy same result Commented Oct 21, 2016 at 19:30

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

End structure should be name: "animals", "sopranos", "guitars"
This fulfills the quoted criteria but I'm looking for that specific structure
0

Replace

obj.name = arr[i][0] 

with

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

4 Comments

"TypeError: Cannot set property 'name' of undefined. Is it not possible to create the name property with bracket notation as obj.name = does...
Yes. It was replaced verbatim
Correction. omitted first line.
It threw only when ob[i] = {} was ommitted, and / or declared outside the loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.