Variable as the property name in a JavaScript object literal?

Javascript

Javascript Problem Overview


> Possible Duplicate:
> How do I add a property to a Javascript Object using a variable as the name?
> Use variable for property name in JavaScript literal?

Is it possible to add a variable as the property name of an object in JavaScript, like this:

var myVar = "name";
var myObject = {
    {myVar}: "value"
};

Javascript Solutions


Solution 1 - Javascript

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"
};

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.

Solution 2 - Javascript

Like this?

var myVar = "name";
var myObject = {};

myObject[myVar] = "value";

Solution 3 - Javascript

Yes, but not directly.

var myVar = "name";
var object = {};
object[myVar] = "value";

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjsgrooveView Question on Stackoverflow
Solution 1 - JavascriptThiefMasterView Answer on Stackoverflow
Solution 2 - JavascriptBlenderView Answer on Stackoverflow
Solution 3 - JavascriptNiet the Dark AbsolView Answer on Stackoverflow