Using Dynamic Property Names in Object Initialization with ES6
The challenge of creating objects with property names derived from external sources often arises in programming. In the scenario described in our query, we attempt to construct a JavaScript object with properties whose keys are defined in a separate variable, KEYS.
However, when assigning values to the properties within the object, we encounter an error due to the use of the dot operator (.). This operator is reserved for literal object property names and cannot be used with dynamic property names.
To address this issue, we turn to the power of ES6 (EcmaScript 2016), a recent addition to JavaScript standards that introduces more expressive syntax and features. One of these features is the computed property syntax, which allows us to dynamically define property names.
Using the computed property syntax, we can rewrite the code as follows, which will successfully create an object with the desired dynamic property names:
iconMap: { [KEYS.PHONE_TYPE]: 'icon-phone', [KEYS.AGENT_TYPE]: 'icon-headphones', },
In this code, the square brackets ([]) around the property names indicate that we are using computed property syntax. The expression inside the brackets evaluates to the dynamic property name, which is retrieved from the KEYS variable.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3