javascripthashcoding-stylenaming

How to rewrite hash assignment in more elegant way


In my code I use

callMethodWithHash({ 'key': "value" });

Things work fine until 'key' assigned to another variable (keyHolder). In that case obvious solution:

var keyHolder = 'key';
callMethodWithHash(keyHolder: "value");

doesn't work (how to assign variable value as variable name in a hash?) and I need to write a few more lines:

var keyHolder = 'key';
var hash = {};
hash[keyHolder] = "value";
callMethodWithHash(hash);

I'm learning JS and would like to develop a good style, but feel like these 3 lines are unnecessary long.

Is there more efficient way to create and pass hash?


Solution

  • var keyHolder = "key",
        hash = { [keyHolder]: "value" };
    
    console.log(hash); 
    

    Keep in mind, that this became available only from ES6. You can always see its compatibility here. In this particular case you should look the computed property name feature, it is in object literal extensions section, called: computed properties.