Creating an object with dynamic property names

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 does not work with the message: Expected ':' and instead saw '.'.

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

To be clear, I want:

 { 'phone-type' : 'icon-phone', 'agent-type' : 'icon-headphones' } 
+6
source share
2 answers

You will need to add these properties separately using the notation in parentheses:

 var myAppConfig = { ... iconMap : { } ... }; myAppConfig.iconMap[ KEYS.PHONE_TYPE ] = 'icon-phone'; myAppConfig.iconMap[ KEYS.AGENT_TYPE ] = 'icon-headphones'; 
+7
source

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

 iconMap : { [KEYS.PHONE_TYPE] : 'icon-phone', [KEYS.AGENT_TYPE] : 'icon-headphones' }; 
+4
source

Source: https://habr.com/ru/post/950177/


All Articles