Javascript expression to define object's property name?

后端 未结 2 868
后悔当初
后悔当初 2020-12-10 20:44

I\'d like to create this object...

object = {
  \'object[1][var_name_1]\' : \'value1\',
  \'object[1][var_name_2]\' : \'value2\',
};

I\'m t

相关标签:
2条回答
  • 2020-12-10 20:55

    In an object literal, each property name can only be identifier rather than an expression, which means you can't use variables. You can only use the square bracket notation on an existing object, so if you have a variable you wish to use as a property name then you'll need to do it after the object is created:

    var object = {
        '1': {};
    };
    
    object[1][var_name_1] = 'value1';
    object[1][var_name_2] = 'value2';
    
    0 讨论(0)
  • You cant set variable properties using literal syntax, but you can set properties using [], after you've created the object:

    myObject = {}
    myObject["any_string_here"] = myValue
    
    0 讨论(0)
提交回复
热议问题