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

ES6 introduces computed property names, which allow you to do

var myObj = {[a]: b};

Note browser support is currently negligible.


Ecu, if you do myObj.a, then it looks for the property named a of myObj. If you do myObj[a] =b then it looks for the a.valueOf() property of myObj.


There's the dot notation and the bracket notation

myObj[a] = b;

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")