Home >Web Front-end >JS Tutorial >How to Create JavaScript Objects with Dynamic Property Names?

How to Create JavaScript Objects with Dynamic Property Names?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 12:35:11129browse

How to Create JavaScript Objects with Dynamic Property Names?

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!

Statement:
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