Dynamic keys in Javascript associative array declaration one-liner

I found a solution for this.

Do as following:

var field='name';

var ourVar={};

ourVar[field] = 'Somethig';

Source: Javascript: variable as array key


It is now possible to use dynamic keys in the declaration of a javascript object, in any browser/platform that supports ES6 literal shorthands:

key = "dynamic";    
arr2 = {
    [key]: "foo",  // "dynamic": "foo"
    "bar": "baz"
};

Only the [] syntax works for dynamic keys. You cannot use them in a literal. So your answer is no, it's not possible.

But you can use a literal to create all the static keys and then add the dynamic ones using the [] syntax. That's usually prettier than using the . or [] notation for all elements.


Since you asked for a one liner, try this:

var key = 'dynamic', obj = (function(o) { o[key]='foo'; return o;})({bar: 'baz'});

This will make obj equal to {bar: "baz", dynamic: "foo"}

Tags:

Javascript