views:

360

answers:

2

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 : ""
    } 
+5  A: 
for ( var i = 0, l = arr.length; i < l; ++i ) {
    literal[arr[i]] = "something";
}

I also took the liberty of optimising your loop :)

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

Use this in your loop:

literal[arr[i]] = "";
Alsciende