I want convert enum type to Array
example :
enum A {
dog = 1,
cat = 2,
ant = 3
}
convert to: [{id: 1, name: 'dog'}, {id: 2, name: 'cat'}, {id: 3, name: 'ant'}]
thank you.
@narutomxc
This is an issue tracker, not a standard help forum. But anyways, here's how you'd do it:
// This requires TypeScript 2.1.
// If you need older versions, use `string` instead of `keyof E`.
interface EnumItem<E> { id: E; name: keyof E; }
function enumToArray<E>(Enum: {[keyof E]: E}): EnumItem<E>[] {
return Object.keys(Enum).map(key => ({id: Enum[key], name: key} as EnumItem<E>))
}
OK, thx
I found {[keyof E]: E}
cannot be recognise in Webstorm. so replace it with any...
Most helpful comment
@narutomxc
This is an issue tracker, not a standard help forum. But anyways, here's how you'd do it: