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

前端 未结 8 2247
暗喜
暗喜 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"
    };
    
    0 讨论(0)
  • 2020-11-27 14:14

    In ES6, use computed property names.

    const key = "anything";   
    
    const object = {   
        [key]: "key attribute"
    //  ^^^^^  COMPUTED PROPERTY NAME
    };
    

    Note the square brackets around key. You can actually specify any expression in the square brackets, not just a variable.

    0 讨论(0)
  • 2020-11-27 14:17

    Solution:

    var key = "anything";
    
    var json = {};
    
    json[key] = "key attribute";
    
    0 讨论(0)
  • 2020-11-27 14:21

    Yes. You can use:

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

    Or simply use your second method if you have the values at hand when writing the program.

    0 讨论(0)
  • 2020-11-27 14:21

    Closures work great for this.

    function keyValue(key){
      return function(value){
        var object = {};
        object[key] = value;
        return object;
      }
    }
    
    var key = keyValue(key);
    key(value);
    
    0 讨论(0)
  • 2020-11-27 14:22

    This should do the trick:

    var key = "anything";
    
    var json = {};
    
    json[key] = "key attribute";
    
    0 讨论(0)
提交回复
热议问题