10

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Michael IV
  • 11,016
  • 12
  • 92
  • 223
  • 1
    `var statesDict = { [State.ACTIVE]: {color:0x00ff00}, ... }`. You can't do substitution for property name variables without the brackets. – Heretic Monkey May 20 '18 at 17:54
  • @RokoC.Buljan No, you can create property names without the quotes for object literals... – Heretic Monkey May 20 '18 at 17:57
  • Quick note: You can only use strings as dictionary keys and anything else, except for [Symbols](https://developer.mozilla.org/en-US/docs/Glossary/Symbol), will be converted via the `toString` function. – schroffl May 20 '18 at 17:58
  • @RokoC.Buljan I prefer keeping things which are not string as not strings )) – Michael IV May 20 '18 at 17:58

1 Answers1

15

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Based on the output I see the key is a string now. Is it the way Js works with types? I can't keep keys as integers? Or "types" have no meaning in Js? )) – Michael IV May 20 '18 at 18:00
  • You can. Here you are trying to evaluate some expression to a Number. Generally yes, Numbers can be keys. (they will be converted to strings) – Attersson May 20 '18 at 18:02
  • 1
    all keys of objects, even indices of arrays are strings. – Nina Scholz May 20 '18 at 18:02
  • @NinaScholz Great,thanks for the clarification. Js is weird language. – Michael IV May 20 '18 at 18:04
  • 1
    @MichaelIV: JS now has a [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) type, which would be better here if ES6 can be used. They don't get converted to strings when used as object properties. `{ DEFAULT: Symbol(), ACTIVE: Symbol(), INACTIVE: Symbol(), ALERT: Symbol() }` It also has a `Map` type, which can be used for your `statesDict`, so you could do `statesDict.get(State.ACTIVE))` –  May 20 '18 at 18:16