How to create an object property from a variable value in JavaScript? [duplicate] How to create an object property from a variable value in JavaScript? [duplicate] javascript javascript

How to create an object property from a variable value in JavaScript? [duplicate]


ES6 introduces computed property names, which allow you to do

var myObj = {[a]: b};

Note browser support is currently negligible.


Dot notation and the properties are equivalent. So you would accomplish like so:

var myObj = new Object;var a = 'string1';myObj[a] = 'whatever';alert(myObj.string1)

(alerts "whatever")