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";
var b = "foo";
var a = { [b]: "bar" };
Such that the result would be
// => {foo: "bar"}
Acceptable solutions are in JavaScript or CoffeeScript
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With