Home >Web Front-end >JS Tutorial >How Can I Create JavaScript Objects with Dynamic Property Names at Runtime?
In programming, it can be useful to create objects with property names that are not known until runtime. This article addresses the challenge of initializing an object with indirect (non-literal) keynames.
Traditionally, JavaScript objects are initialized with fixed, literal property names:
var myAppConfig = { iconMap: { "phone-type": "icon-phone", "agent-type": "icon-headphones" } };
However, in certain scenarios, dynamic property names are required. For example, the property names may be stored in a different object.
If you are using ES6 or a transpiler like Babel, you can utilize computed property names:
var iconMap = { [KEYS.PHONE_TYPE]: 'icon-phone', [KEYS.AGENT_TYPE]: 'icon-headphones' };
In this syntax, the property name is enclosed in square brackets and evaluated as an expression. The value of KEYS.PHONE_TYPE is used as the property name for the first key-value pair.
As a result, the iconMap object will be initialized with the expected dynamic property names:
{ 'phone-type': 'icon-phone', 'agent-type': 'icon-headphones' }
This approach allows you to create objects with non-literal property names at runtime, providing greater flexibility and code adaptability.
The above is the detailed content of How Can I Create JavaScript Objects with Dynamic Property Names at Runtime?. For more information, please follow other related articles on the PHP Chinese website!