Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 469
Tolga E Avatar asked Aug 09 '13 15:08

Tolga E


People also ask

How do you find the value of an enum in an array?

To get all enum values as an array, pass the enum to the Object. values() method, e.g. const values = Object. values(StringEnum) .

Can I use enum as array index?

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.

Can enums be arrays?

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.


2 Answers

Simple solution (ES6)

You can use Object.values like this:

var valueArray = Object.values(types); 

Online demo (fiddle)

like image 184
Ali Soltani Avatar answered Oct 16 '22 15:10

Ali Soltani


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; } 
like image 43
Yann Avatar answered Oct 16 '22 15:10

Yann