6

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'
};
1
  • 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' Commented Aug 31, 2018 at 15:28

1 Answer 1

16

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);

Sign up to request clarification or add additional context in comments.

2 Comments

fantastic just what I wanted.
just a note, I was curious what is this syntax, turns out it's called "computed property names", see more info here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.