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

3 Answers 3

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

I also took the liberty of optimising your loop :)

Sign up to request clarification or add additional context in comments.

3 Comments

Even more compact would be for(var i in arr) { literal[arr[i]] = ''; } :)
@Tatu, you shouldn't loop through arrays using the for..in construct.
Better would be var i = arr.length; while (i--) { literal[arr[i]] = "something" }
4

Use this in your loop:

literal[arr[i]] = "";

Comments

0

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

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

2 Comments

Shouldn't it be let key?
@marko You can use const instead of let, if you don't reassign the variable inside the block, but this is not the case here, just accessing its value directly.

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.