19

I would expect the following three associative arrays to be identical:

arr1 = { "dynamic":"foo", "bar":"baz" };

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

arr3 = {};
arr3[key] = "foo";
arr3["bar"] = "baz";

In the above examples, arr1 and arr3 are the same, but arr2 is different.

Is it possible to use dynamic keys in the declaration of a javascript associative array?

ajwood
  • 18,227
  • 15
  • 61
  • 104
  • 1
    No you cannot use variables as keys in an object literal declaration. – Musa Jul 24 '13 at 17:09
  • [N](http://stackoverflow.com/q/6500573/1048572)[o](http://stackoverflow.com/q/4071499/1048572) – Bergi Jul 24 '13 at 17:30
  • duplicate of [Using a variable for a Javascript object key](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-javascript-object-key) (and many others) – Bergi Jul 24 '13 at 17:38

5 Answers5

20

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"
};
Brian
  • 7,394
  • 3
  • 25
  • 46
9

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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
7

I found a solution for this.

Do as following:

var field='name';

var ourVar={};

ourVar[field] = 'Somethig';

Source: Javascript: variable as array key

Community
  • 1
  • 1
Ramasamy Kasi
  • 171
  • 3
  • 3
1

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"}

Phil M
  • 975
  • 1
  • 9
  • 13
0
var originalObj = {};//some data here


function addKeyValuePair(originalObj,key,value){
    originalObj = {...originalObj,[key]:value}
};