Consider the following
var a = {foo: \"bar\"};
Equivalent to
var a = {};
a.foo = \"bar\";
Equivalent to
To answer your question, this is the only way that I know of. It uses eval
. But beware, eval
is evil!
var b = "foo";
var a = eval('({ ' + b + ': ' + '"bar"' + ' })');
This is an ugly solution. To play it safe you should not rely on this. Don't use it!
As others have said, no, there's currently no syntax for interpolated key strings in object literals in CoffeeScript; but it seems at some point this feature existed! In these GitHub issues there's some discussion about it: #786 and #1731.
It's implemented in Coco and LiveScript as:
b = 'foo'
a = {"#{b}": 'baz'}
# Or..
a = {(b): 'bar'}
JavaScript
var a, b;
(a = {})[b = 'foo'] = 'bar';
CoffeeScript
(a = {})[b = 'foo'] = 'bar'
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.
As of CoffeeScript version 1.9.1 this works:
b = "foo"
a = "#{b}": "bar"
It compiles to:
var a, b, obj;
b = "foo";
a = (
obj = {},
obj["" + b] = "bar",
obj
);
Try it.
JSON parse allows you to convert a JSON string into an object:
JSON.parse('{"'+dynamicProperty+'":"bar"}');
This is not exactly an object litteral, but if your objective is to enter your property name as a variable it works.