Home >Web Front-end >JS Tutorial >How Can I Dynamically Assign Object Property Names in JavaScript?
An effort to initialize an object using indirect key names produced an error, prompting the question of how to achieve such a feat. The desired outcome involves creating an object with specific key-value pairs where the key names are derived from an external source.
The solution, however, lies in the realm of modern JavaScript. Using the ES6 syntax and its object literal enhancements, it is possible to dynamically construct object properties based on variables:
iconMap: { [KEYS.PHONE_TYPE]: 'icon-phone', [KEYS.AGENT_TYPE]: 'icon-headphones', };
In this example, the object property names correspond to the values stored in the KEYS object. The square brackets encapsulating the variable KEYS.PHONE_TYPE enable the property's name to be dynamically derived at runtime.
The above is the detailed content of How Can I Dynamically Assign Object Property Names in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!