Dynamic Property Names in Object Initialization
One may encounter issues when initializing an object using non-literal keynames. For example, the following code fails with an error message about an expected ':' character:
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' }; ... };
Solution for ES6
Using ES6 syntax, dynamic property names can be created using square brackets. The updated code would look like this:
iconMap : { [KEYS.PHONE_TYPE] : 'icon-phone', [KEYS.AGENT_TYPE] : 'icon-headphones' };
This approach allows for the creation of objects with dynamic property names by enclosing the desired property name within square brackets.
The above is the detailed content of How Can I Use Dynamic Property Names When Initializing Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!