반응형
enum을 값 배열로 변환(배열 내 모든 JSON 값 배치)
JavaScript에서 이 메서드 Enums를 사용합니까?코드에 에넘을 작성하기 위해
그렇게
var types = {
"WHITE" : 0,
"BLACK" : 1
}
여기서 문제는 검증을 어디서든 작성하려면 이 작업을 수행해야 한다는 것입니다.
model.validate("typesColumn", [ types.WHITE, types.BLACK ]);
열거형 값을 모두 나열하지 않아도 되도록 단순히 유형 값을 배열로 변환할 수 있는 방법이 있습니까?
model.validate("typesColumn", types.ValuesInArray]);
편집: 간단한 Enum을 생성하기 위해 매우 간단한 열거 라이브러리를 만들었습니다.npm --save-dev install simple-enum(https://www.npmjs.com/package/simple-enum)
심플한 솔루션 (ES6)
사용할 수 있습니다.Object.values다음과 같습니다.
var valueArray = Object.values(types);
지도를 배열로 변환하여 다음과 같이 저장합니다.types.all. 자동으로 수행하는 방법을 만들 수 있습니다.
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);
어레이로 변환할 수도 있고 오브젝트의 속성만 반복할 수도 있습니다(어레이를 작성하는 방법).
for(var i in types){
var type = types[i];
//in the first iteration: i = "WHITE", type = 0
//in the second iteration: i = "BLACK", type = 1
}
이 방법으로 어레이를 작성할 수 있는 방법은 다음과 같습니다.
var arr = [];
for(var i in types){
var type = types[i];
arr.push(type);
}
//arr = [0, 1]
이것을 재사용하려면 , 도우미 기능을 작성할 수 있습니다.
function ObjectToValueArray(obj){
var arr = [];
for(var i in obj){
var v = obj[i];
arr.push(v);
}
return arr;
}
이것은 다음과 같이 말할 수 있습니다.
model.validate("typesColumn", ObjectToValueArray(types));
주스업(또는 랩업).validate받아들일 수 있도록types멤버 전체로요?
var types = {
"WHITE" : 0,
"BLACK" : 1,
"RED" : 200
}
validate("foo", types.WHITE); // 0
validate("foo", [types.WHITE, types.BLACK]); // 0,1
validate("foo", types); // 0,1,200
function validate(foo, values) {
var arr = [];
switch (typeof values) {
case "number":
arr.push(values);
break;
case "object":
if (values instanceof Array)
arr = values;
else {
for (var k in values)
arr.push(values[k]);
}
break;
}
alert(arr);
}
언급URL : https://stackoverflow.com/questions/18150659/converting-enums-to-array-of-values-putting-all-json-values-in-an-array
반응형
'programing' 카테고리의 다른 글
| WordPress remove_menu_page() 함수가 오류를 발생시킵니다. (0) | 2023.03.10 |
|---|---|
| React Dev 도구에 내 구성 요소가 알 수 없음으로 표시됨 (0) | 2023.03.10 |
| 스프링 부트용 임베디드 레디스 (0) | 2023.03.10 |
| WordPress에 정적 페이지를 추가하려면 어떻게 해야 합니까? (0) | 2023.03.10 |
| AngularJS에서 필터 내의 파라미터를 사용하는 방법 (0) | 2023.03.10 |