我有一个这样定义的枚举:
export enum GoalProgressMeasurements {
Percentage = 1,
Numeric_Target = 2,
Completed_Tasks = 3,
Average_Milestone_Progress = 4,
Not_Measured = 5
}
然而,我希望它被表示为一个对象数组/列表从我们的API如下:
[{id: 1, name: 'Percentage'},
{id: 2, name: 'Numeric Target'},
{id: 3, name: 'Completed Tasks'},
{id: 4, name: 'Average Milestone Progress'},
{id: 5, name: 'Not Measured'}]
是否有简单和本地的方法来做到这一点,或者我必须构建一个函数,将枚举转换为int和字符串,并将对象构建为数组?
另一种方法是使用ES8 Object.entries
export enum Weeks {
MONDAY = 1,
TUESDAY= 2,
WEDNESDAY = 3,
THURSDAY = 4,
FRIDAY = 5,
SATURDAY=6,
SUNDAY=7,
}
function convertEnumToArray(){
const arrayObjects = []
// Retrieve key and values using Object.entries() method.
for (const [propertyKey, propertyValue] of Object.entries(Weeks)) {
// Ignore keys that are not numbers
if (!Number.isNaN(Number(propertyKey))) {
continue;
}
// Add keys and values to array
arrayObjects.push({ id: propertyValue, name: propertyKey });
}
console.log(arrayObjects);
}
将产生以下内容:
[
{ id: 1, name: 'MONDAY' },
{ id: 2, name: 'TUESDAY' },
{ id: 3, name: 'WEDNESDAY' },
{ id: 4, name: 'THURSDAY' },
{ id: 5, name: 'FRIDAY' },
{ id: 6, name: 'SATURDAY' },
{ id: 7, name: 'SUNDAY' }
]
无耻地从这个博客偷来的
一个棘手的地方是TypeScript会在触发对象中'double'映射enum,所以它可以通过键和值访问。
enum MyEnum {
Part1 = 0,
Part2 = 1
}
将以
{
Part1: 0,
Part2: 1,
0: 'Part1',
1: 'Part2'
}
所以你应该在映射之前先过滤对象。所以@Diullei的解决方案是正确的。这是我的实现:
// Helper
const StringIsNumber = value => isNaN(Number(value)) === false;
// Turn enum into array
function ToArray(enumme) {
return Object.keys(enumme)
.filter(StringIsNumber)
.map(key => enumme[key]);
}
像这样使用它:
export enum GoalProgressMeasurements {
Percentage,
Numeric_Target,
Completed_Tasks,
Average_Milestone_Progress,
Not_Measured
}
console.log(ToArray(GoalProgressMeasurements));
我已经解出来了。
假设您有一个如下所示的枚举
export enum UnitEnum {
GRAM = 'gm',
KILOGRAM = 'kg',
LITRE = 'lt',
CENTIMETER = 'cm',
INCH = 'in',
METER = 'mt',
KILOMETER = 'km',
}
你有这样一门课,
export interface Unit {
Name: string;
Symbol: string;
}
然后,您可以创建一个如下所示的函数,将异构枚举映射到某个类型的对象,
export function getDefaultUnits() {
const myUnits = Object.entries(UnitEnum).map(x => {
return { Name: x[0], Symbol: x[1] } as Unit
})
console.log(myUnits);
return myUnits;
}