Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an object with dynamic property names [duplicate]

Tags:

javascript

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'
}
like image 574
blueFast Avatar asked Jul 24 '13 11:07

blueFast


2 Answers

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'
};
like image 93
Dragos Bobolea Avatar answered Oct 07 '22 13:10

Dragos Bobolea


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';
like image 31
Sirko Avatar answered Oct 07 '22 14:10

Sirko