Creating Objects with Dynamic Property Names
In JavaScript, objects are typically defined using literal key-value pairs. However, there are instances where you may encounter a scenario where the property names are dynamic or not known at the time of object creation. This can be achieved through the use of bracket notation.
Problem:
Consider the following code snippet:
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' }; ... };
This code fails with the error "Expected ':' and instead saw '.'." This is because you are attempting to access the KEYS object as a property of the myAppConfig object using dot notation (.). To address this issue, you need to use bracket notation [] to access properties dynamically.
Solution:
Using ES6 (or a transpiler like Babel/browserify), you can initialize an object with dynamic property names using bracket notation, as shown below:
iconMap : { [KEYS.PHONE_TYPE] : 'icon-phone', [KEYS.AGENT_TYPE] : 'icon-headphones' };
In this code, the brackets [] around the KEYS properties allow you to dynamically specify the property names based on the values stored in the KEYS object. As a result, the iconMap property of the myAppConfig object will contain the desired mapping of values:
{ 'phone-type' : 'icon-phone', 'agent-type' : 'icon-headphones' }
The above is the detailed content of How to Create JavaScript Objects with Dynamic Property Names?. For more information, please follow other related articles on the PHP Chinese website!