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)
To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) .
It is perfectly normal to use an enum for indexing into an array. You don't have to specify each enum value, they will increment automatically by 1. Letting the compiler pick the values reduces the possibility of mistyping and creating a bug, but it deprives you of seeing the values, which might be useful in debugging.
Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.
Simple solution (ES6)
You can use Object.values
like this:
var valueArray = Object.values(types);
Online demo (fiddle)
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With