Variable as the property name in a JavaScript obje

2018-12-31 12:19发布

This question already has an answer here:

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
3条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 12:33

Yes, but not directly.

var myVar = "name";
var object = {};
object[myVar] = "value";
查看更多
余欢
3楼-- · 2018-12-31 12:37

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"
};
查看更多
梦该遗忘
4楼-- · 2018-12-31 12:46

Like this?

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

myObject[myVar] = "value";
查看更多
登录 后发表回答