Home > Web Front-end > JS Tutorial > How Can I Create JavaScript Objects with Dynamic Property Names at Runtime?

How Can I Create JavaScript Objects with Dynamic Property Names at Runtime?

Linda Hamilton
Release: 2024-11-30 13:15:13
Original
600 people have browsed it

How Can I Create JavaScript Objects with Dynamic Property Names at Runtime?

Using Dynamic Property Names for Object Creation

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.

The Problem: Static Property Names

Traditionally, JavaScript objects are initialized with fixed, literal property names:

var myAppConfig = {
    iconMap: {
        "phone-type": "icon-phone",
        "agent-type": "icon-headphones"
    }
};
Copy after login

However, in certain scenarios, dynamic property names are required. For example, the property names may be stored in a different object.

Using ES6 Computed Property Names

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'
};
Copy after login

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.

Output:

As a result, the iconMap object will be initialized with the expected dynamic property names:

{
    'phone-type': 'icon-phone',
    'agent-type': 'icon-headphones'
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template