Variable as the property name in a JavaScript object literal? [duplicate]
Solution 1:
You can use the []
syntax to use an expression as the property name (compared to the .prop
and prop: value
syntaxes where they are always treated as strings):
var myObject = {};
var myVar = "name";
myObject[myVar] = "value";
There is no way to use that inside an object literal, though. You have to create the object first and then assign each property separately.
Edit
With ES6, this is now possible using a ComputedPropertyName, which manifests in the form of the following syntax:
var myVar = "name";
var myObject = {
[myVar]: "value"
};
Solution 2:
Like this?
var myVar = "name";
var myObject = {};
myObject[myVar] = "value";
Solution 3:
Yes, but not directly.
var myVar = "name";
var object = {};
object[myVar] = "value";