69

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"
};
5
  • 4
  • Well, SO most likely suggested one of them while writing the question... Commented Jun 15, 2012 at 0: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.) Commented Jun 15, 2012 at 0: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. Commented Jun 15, 2012 at 0:19
  • None of those other questions address the issue of using the value of a variable as a property name within an object literal. Commented Jun 2, 2014 at 19:25

3 Answers 3

222

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for words. Words are always nice.
+1 for explicitly mentioning that there is no way to do this within an object literal. (That's the reason we're all here, isn't it?)
And more points for the update so latecomers gets to know that it has since become possible!
12

Like this?

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

myObject[myVar] = "value";

Comments

10

Yes, but not directly.

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

5 Comments

If you want a one-liner: var object = Object.defineProperty( {}, myVar, { value: "value" } );
@IsaacKleinman Then it can't be iterated, overwritten, or deleted.
@Scimonster: you can: var object = Object.defineProperty( {}, myVar, { value: "value", enumerable: true, writable: true, configurable: true } ); still one line. ;)
@IsaacKleinman Fair enough, but by then it's almost longer than this solution. BTW you're missing a comma before enumerable.
I've been looking for how to do that middle step for hours. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.