10

Is it possible to creat an object literal on the fly? Like this:

var arr = [ 'one', 'two', 'three' ]; 

var literal = {}; 

for(var i=0;i<arr.length;i++)
{
   // some literal push method here! 

  /*  literal = {
        one : "", 
        two : "",
        three : ""
    }  */ 
}

Thus I want the result to be like this:

 literal = {
        one : "", 
        two : "",
        three : ""
    } 
marko
  • 10,684
  • 17
  • 71
  • 92

3 Answers3

20
for ( var i = 0, l = arr.length; i < l; ++i ) {
    literal[arr[i]] = "something";
}

I also took the liberty of optimising your loop :)

James
  • 109,676
  • 31
  • 162
  • 175
4

Use this in your loop:

literal[arr[i]] = "";
Alsciende
  • 26,583
  • 9
  • 51
  • 67
0

You can use for...of for the sake of simplicity:

for (const key of arr) {
   literal[key] = "";
}
ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26