Marko
Marko

Reputation: 11002

Dynamic object literal in javascript?

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

Upvotes: 10

Views: 9717

Answers (3)

ProgrammerPer
ProgrammerPer

Reputation: 1191

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

for (const key of arr) {
   literal[key] = "";
}

Upvotes: 0

Alsciende
Alsciende

Reputation: 26981

Use this in your loop:

literal[arr[i]] = "";

Upvotes: 4

James
James

Reputation: 112000

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

I also took the liberty of optimising your loop :)

Upvotes: 20

Related Questions