Dynamic object literal in javascript?

2019-01-23 17:13发布

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条回答
ゆ 、 Hurt°
2楼-- · 2019-01-23 17:50

Use this in your loop:

literal[arr[i]] = "";
查看更多
冷血范
3楼-- · 2019-01-23 17:53
for ( var i = 0, l = arr.length; i < l; ++i ) {
    literal[arr[i]] = "something";
}

I also took the liberty of optimising your loop :)

查看更多
Melony?
4楼-- · 2019-01-23 17:55

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

for (const key of arr) {
   literal[key] = "";
}
查看更多
登录 后发表回答