我有一个这样定义的枚举:
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和字符串,并将对象构建为数组?
我不认为顺序是可以保证的,否则就很容易切片Object的后半部分。条目的结果和映射来自那里。
上述答案的唯一(非常小的)问题是
字符串和数字之间有很多不必要的类型转换。
当一次迭代同样干净有效时,条目将迭代两次。
type StandardEnum = { [id: string]: number | string; [nu: number]: string;}
function enumToList<T extends StandardEnum> (enm: T) : { id: number; description: string }[] {
return Object.entries(enm).reduce((accum, kv) => {
if (typeof kv[1] === 'number') {
accum.push({ id: kv[1], description: kv[0] })
}
return accum
}, []) // if enum is huge, perhaps pre-allocate with new Array(entries.length / 2), however then push won't work, so tracking an index would also be required
}
我已经解出来了。
假设您有一个如下所示的枚举
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;
}