1

Is it possible to name a object property directly inside the object declaration itself, insted of doing it afterwards?

For examle, this works:

var name  = "foo";
var obj   = {};
obj[name] = "bar; // obj.foo === "bar"

But is there a way to do it somehow inside the object itself, like:

var name  = "foo";
var obj   = {
    name: "bar" // obj.name === "bar"
};

I know it is possible to use strings for property names, so I was thinking something like this should do as workaround, but it didn't:

var obj   = {
    "" + name: "bar"
};

Is there a way to do this?

eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • Do you have a preferred duplicate? How about http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal? –  Oct 05 '16 at 14:34
  • @eisbehr: this has been asked and answered about 1e10 times before, please use the search next time – georg Oct 05 '16 at 14:36

1 Answers1

2

There is in ES2015, otherwise in ES5, there is no way to do that

var name = "foo";
var obj = {
  [name]: "bar"
};

console.log(obj)

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already. Now you can use the same syntax in object literals, too.

Computed properties in object initializers on MDN

eisbehr
  • 12,243
  • 7
  • 38
  • 63
adeneo
  • 312,895
  • 29
  • 395
  • 388