3

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'
};
user3284707
  • 3,033
  • 3
  • 35
  • 69
  • 1
    You might need to use the object initialization syntanx differently by wrapping those keys in brackets: `{ [ACTIVE]: 'Active }` for example. The value of the variable is copied into the object, without the `const` qualifier. Really what you're attempting to do (if I understand correctly) is creating a key where `userStatus[1] = 'Active'`, not `userStatus.ACTIVE = 'Active'` – Peter Van Drunen Aug 31 '18 at 15:28

1 Answers1

12

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);
Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
NullPointer
  • 7,094
  • 5
  • 27
  • 41