0

The problem I'm trying to solve is creating a dynamic object initiallizer im pretty sure it's called. Instead of hardcoding in a number in the object since I don't know the outcome of the number. A code example will demonstrate the example.

Ive tried to create a simple for loop to interate through a number to display in the console later on but nothing successful so far.

 for(var counter =0; counter <3; counter++){
    var myObject = {counter : "Text"};
    console.log(myObject)
 }

But the output shows the actual variable name instead of the number it contains. The output needs to be exactly like this example: {0:"Example"}.

Output in the console window in Chrome: {counter: "Text"} {counter: "Text"} {counter: "Text"}

u_mulder
  • 54,101
  • 5
  • 48
  • 64
Robin Larsson
  • 31
  • 1
  • 6

1 Answers1

5

You have to use the bracket notation [] to use variables as keys(dynamic keys) in objects

for (var counter = 0; counter < 3; counter++) {
  var myObject = {
    [counter]: "Text"
  };
  console.log(myObject)
}
ellipsis
  • 12,049
  • 2
  • 17
  • 33