9

I am trying to do this:

var KEYS = {} ;

KEYS.PHONE_TYPE = 'phone-type';
KEYS.AGENT_TYPE = 'agent-type';

var myAppConfig = {
    ...
    iconMap : { 
        KEYS.PHONE_TYPE : 'icon-phone', 
        KEYS.AGENT_TYPE : 'icon-headphones'
    };
    ...
};

But it is failing, with a message: Expected ':' and instead saw '.'.

How can I initialize an object using indirect (non-literal) keynames?

To be clear, the result I want is:

{
    'phone-type' : 'icon-phone',
    'agent-type' : 'icon-headphones'
}
blueFast
  • 37,437
  • 54
  • 182
  • 318

2 Answers2

13

If you're using ES6 (or something like Babel/browserify), you can write it like this:

iconMap : { 
    [KEYS.PHONE_TYPE] : 'icon-phone', 
    [KEYS.AGENT_TYPE] : 'icon-headphones'
};
Dragos Bobolea
  • 772
  • 7
  • 16
7

You would have to add those properties separately using bracket notation:

var myAppConfig = {
    ...
    iconMap : { }
    ...
};

myAppConfig.iconMap[ KEYS.PHONE_TYPE ] = 'icon-phone';
myAppConfig.iconMap[ KEYS.AGENT_TYPE ] = 'icon-headphones';
Sirko
  • 69,531
  • 19
  • 142
  • 174
  • 1
    Thanks. I am still surprised that javascript has no built-in support for initialization of an object with dynamic keynames. Python can do this for dictionaries, and it is very convenient. I guess this comes from the fact that the quotes are optional in javascript properties. – blueFast Jul 24 '13 at 11:31
  • I guess JS abandoned that possibility by allowing unquoted attribute names, Python avoids this by requiring quoted attribute names. – Petruza Dec 19 '14 at 20:14