Is it possible to define a dynamically named property using an object literal in JavaScript?

Consider the following

var a = {foo: "bar"}; 

Equivalent

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

Equivalent

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

Equivalent

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

Is it possible to do something like

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

Thus, the result will be

 // => {foo: "bar"} 

Acceptable JavaScript or CoffeeScript Solutions

+8
javascript coffeescript
source share
7 answers

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 in [] to specify a property name

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

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

+4
source share

Not.

There is no way to do this using object notation. C>


UPDATE: According to ECMAScript standard 6.0, you can now do the following:

 var b = 'foo'; var a = { [b]: 'bar' }; console.log( a.foo ); // "bar" 

However, this solution will not work in older browsers that do not support ES6 .

+5
source share

JSON parse allows you to convert a JSON string to an object:

 JSON.parse('{"'+dynamicProperty+'":"bar"}'); 

This is not quite an object lettering, but if your goal is to enter your property name as a variable, it works.

+4
source share

As others have said, no, there is currently no syntax for interpolated key strings in object literals in CoffeeScript; but it seems that at some point this function existed! There is some discussion on these GitHub issues: # 786 and # 1731 .

It is implemented in Coco and LiveScript as

 b = 'foo' a = {"#{b}": 'baz'} # Or.. a = {(b): 'bar'} 
+3
source share

How from CoffeeScript version 1.9.1 it works:

 b = "foo" a = "#{b}": "bar" 

It compiles to:

 var a, b, obj; b = "foo"; a = ( obj = {}, obj["" + b] = "bar", obj ); 

Give it a try .

+1
source share

Javascript

 var a, b; (a = {})[b = 'foo'] = 'bar'; 

CoffeeScript

 (a = {})[b = 'foo'] = 'bar' 
0
source share

To answer your question, this is the only way I know about. It uses eval . But be careful, eval evil!

 var b = "foo"; var a = eval('({ ' + b + ': ' + '"bar"' + ' })'); 

This is an ugly decision. To play it safely, you should not rely on it. Do not use !

-one
source share

All Articles