问题
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
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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'}
回答5:
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.
回答6:
JavaScript
var a, b;
(a = {})[b = 'foo'] = 'bar';
CoffeeScript
(a = {})[b = 'foo'] = 'bar'
回答7:
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!
来源:https://stackoverflow.com/questions/13997748/is-it-possible-to-define-a-dynamically-named-property-using-object-literal-in-ja