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)
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;
}
var types = {
"WHITE" : 0,
"BLACK" : 1
}
var typeArray = Object.keys(types).map(function(type) {
return types[type];
});
//typeArray [0,1]
model.validate("typesColumn", typeArray);
jsFiddle演示
Simple solution (ES6)
You can use Object.values
like this:
var valueArray = Object.values(types);
Online demo (fiddle)
链接地址: http://www.djcxy.com/p/91764.html上一篇: AngularJS中枚举的最佳解决方案?