Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a dynamically named property using object literal in JavaScript? [duplicate]

Consider the following

var a = {foo: "bar"};

Equivalent to

var a = {};
a.foo = "bar";

Equivalent to

var a = {};
a['foo'] = "bar";

Equivalent to

var a = {}
var b = "foo";
a[b] = "bar";

Is it possible to do something like

var b = "foo";
var a = { [b]: "bar" };

Such that the result would be

// => {foo: "bar"}

Acceptable solutions are in JavaScript or CoffeeScript

like image 243
Mulan Avatar asked Dec 21 '12 22:12

Mulan


2 Answers

No.

There is no way to do it using object literal notation.


UPDATE: According to the ECMAScript standard 6.0 you are now able to do the following:

var b = 'foo';
var a = { [b]: 'bar' };

console.log( a.foo );  // "bar"

However, this solution won't work in old browsers, which do not support ES6.

like image 162
VisioN Avatar answered Oct 02 '22 15:10

VisioN


ES6 supports computed properties.

// code from my original question now works in ES6 !
let b = "foo";
let a = { [b]: "bar" };

a.foo; //=> "bar"

Any expression can be used within the [] to define the property name

let a = {
  [(xs => xs.join(''))(['f','o','o'])]: 'bar'
};

a.foo; //=> "bar"

If you need to rely on this behavior in an ES5 world, you can lean on the very capable babel.js to transpile your ES6 code to ES5-compatible code.

like image 36
Mulan Avatar answered Oct 02 '22 15:10

Mulan