Is it possible to define a dynamically named property using object literal in JavaScript?

后端 未结 7 1653
南旧
南旧 2021-01-17 16:05

Consider the following

var a = {foo: \"bar\"};

Equivalent to

var a = {};
a.foo = \"bar\";

Equivalent to

7条回答
  •  清歌不尽
    2021-01-17 16:32

    JSON parse allows you to convert a JSON string into an object:

    JSON.parse('{"'+dynamicProperty+'":"bar"}');
    

    This is not exactly an object litteral, but if your objective is to enter your property name as a variable it works.

提交回复
热议问题