10

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'
}
4

2 Answers 2

14

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'
};
Sign up to request clarification or add additional context in comments.

Comments

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';

2 Comments

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.
I guess JS abandoned that possibility by allowing unquoted attribute names, Python avoids this by requiring quoted attribute names.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.