Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum object as dictionary key [duplicate]

Tags:

javascript

I want to use a so called "enum" object as dictionary key,(actually,it is also a dictionary AFAIK), in JavaScript.

This doesn't work:

    var State ={DEFAULT:0,ACTIVE:1 ,INACTIVE:2,ALERT:3};

    var statesDict =  {
      State.ACTIVE : {color:0x00ff00}
      State.INACTIVE: {color:0x000000}
    };

while this one does:

   var State ={DEFAULT:0,ACTIVE:1 ,INACTIVE:2,ALERT:3};

    var statesDict =  {
      1: {color:0x00ff00}
      2: {color:0x000000}
    };

Why? Isn't the State.{prop name} supposed to be replaced by its value?

like image 963
Michael IV Avatar asked May 20 '18 17:05

Michael IV


1 Answers

You could use computed property names with brackets.

var State = { DEFAULT: 0, ACTIVE: 1, INACTIVE: 2, ALERT: 3 },
    statesDict = {
        [State.ACTIVE]: { color: 0x00ff00 },
        [State.INACTIVE]: { color: 0x000000 }
    };

console.log(statesDict);
like image 195
Nina Scholz Avatar answered Sep 30 '22 04:09

Nina Scholz