Search code examples
javascriptconstants

Can I use constant values in key value pair object in javascript


I would like to define a set of constants, which I then use the values of in another javascript object. I have the below example.

This however doesn't seem to work when I am trying to use 0 as a key for example.

Is there a way to get this to work?

export const PENDING_ACTIVATION = 0;
export const ACTIVE = 1;
export const SUSPENDED = 2;

export const userStatus = {
    PENDING_ACTIVATION : 'Pending Activation',
    ACTIVE : 'Active',
    SUSPENDED : 'Inactive'
};

Solution

  • Use [key] notation to create keys at the time of object initialization.

    const PENDING_ACTIVATION = 0;
    const ACTIVE = 1;
    const SUSPENDED = 2;
    
    const userStatus = {
        [PENDING_ACTIVATION] : 'Pending Activation',
        [ACTIVE]: 'Active',
        [SUSPENDED] : 'Inactive'
    };
    console.log(userStatus);