Home > Web Front-end > JS Tutorial > How Can I Use Dynamic Property Names When Initializing Objects in JavaScript?

How Can I Use Dynamic Property Names When Initializing Objects in JavaScript?

Barbara Streisand
Release: 2024-12-05 14:49:09
Original
227 people have browsed it

How Can I Use Dynamic Property Names When Initializing Objects in JavaScript?

Dynamic Property Names in Object Initialization

One may encounter issues when initializing an object using non-literal keynames. For example, the following code fails with an error message about an expected ':' character:

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

Solution for ES6

Using ES6 syntax, dynamic property names can be created using square brackets. The updated code would look like this:

iconMap : { 
    [KEYS.PHONE_TYPE] : 'icon-phone', 
    [KEYS.AGENT_TYPE] : 'icon-headphones'
};
Copy after login

This approach allows for the creation of objects with dynamic property names by enclosing the desired property name within square brackets.

The above is the detailed content of How Can I Use Dynamic Property Names When Initializing Objects in JavaScript?. 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