67

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"
};
Community
  • 1
  • 1
jsgroove
  • 1,457
  • 2
  • 14
  • 17
  • 4
    http://stackoverflow.com/questions/1567278/use-javascript-variable-in-object-name?rq=1 , http://stackoverflow.com/questions/2855473/javascript-expression-to-define-objects-property-name?rq=1 , http://stackoverflow.com/questions/4694652/javascript-creating-object-and-assigning-variable-for-property-name?rq=1 , http://stackoverflow.com/questions/9367572/javascript-object-literal-keys , http://stackoverflow.com/questions/7638659/javascript-property-and-object?rq=1 –  Jun 15 '12 at 00:07
  • Well, SO most likely suggested one of them while writing the question... – ThiefMaster Jun 15 '12 at 00:08
  • 1
    -1 I gave a downvote because there is an *overwhelming* number of similar questions. (The term "literal" might also be good in a search, as it will reveal that this can't be done in a literal.) –  Jun 15 '12 at 00:08
  • I was asking about the possibility of including the variable directly in the object writing, like my example, a thing that is not referenced in the threads mentioned. I will presume that this is not possible then. – jsgroove Jun 15 '12 at 00:19
  • None of those other questions address the issue of using the value of a variable as a property name within an object literal. – Isaac Kleinman Jun 02 '14 at 19:25

3 Answers3

217

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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
12

Like this?

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

myObject[myVar] = "value";
Blender
  • 289,723
  • 53
  • 439
  • 496
10

Yes, but not directly.

var myVar = "name";
var object = {};
object[myVar] = "value";
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592