Search code examples
javascriptloopsfor-loopjavascript-objects

Cannot see the number on the left hand of an object side in console log


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"}


Solution

  • 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)
    }