Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to convert enum type to Array<Object> #12877

Closed
attachai-b opened this issue Dec 13, 2016 · 3 comments
Closed

How to convert enum type to Array<Object> #12877

attachai-b opened this issue Dec 13, 2016 · 3 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@attachai-b
Copy link

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.

@dead-claudia
Copy link

@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>))
}

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Dec 13, 2016
@mhegazy mhegazy closed this as completed Dec 13, 2016
@attachai-b
Copy link
Author

OK, thx

@xmeng1
Copy link

xmeng1 commented Nov 1, 2017

I found {[keyof E]: E} cannot be recognise in Webstorm. so replace it with any...

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

4 participants