Is there a way to use variable keys in a JavaScript object literal?

前端 未结 8 2311
暗喜
暗喜 2020-11-27 13:38

I have code like this.

var key = \"anything\";   
var object = {   
    key: \"key attribute\"  
};

I want to know if there is a way to rep

8条回答
  •  渐次进展
    2020-11-27 14:10

    On modern Javascript (ECMAScript 6) you can sorround the variable with square brackets:

    var key = "anything";
    
    var json = {
        [key]: "key attribute"
    };
    

提交回复
热议问题