javascriptjsonnode.jsenums

Converting enums to array of values (Putting all JSON values in an array)


I use this method Enums in JavaScript? to create enums in our code..

So

var types = {
  "WHITE" : 0,
  "BLACK" : 1
}

Now the issue is when I want create validations anywhere, I have to do this;

model.validate("typesColumn", [ types.WHITE, types.BLACK ]);

Now is there a way I can just simple convert the values in types to an array so that I don't have to list all of the values of the enum?

model.validate("typesColumn", types.ValuesInArray]);

EDIT: I created a very simple enum library to generate simple enums npm --save-dev install simple-enum (https://www.npmjs.com/package/simple-enum)


Solution

  • I would convert the map into an array and store it as types.all. You can create a method that does it automatically:

    function makeEnum(enumObject){
       var all = [];
       for(var key in enumObject){
          all.push(enumObject[key]);
       }
       enumObject.all = all;
    }