Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic keys in Javascript associative array declaration one-liner

Tags:

javascript

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?

like image 471
ajwood Avatar asked Jul 24 '13 17:07

ajwood


2 Answers

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"
};
like image 141
Brian Avatar answered Sep 20 '22 17:09

Brian


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.

like image 23
ThiefMaster Avatar answered Sep 20 '22 17:09

ThiefMaster