Skip to content
typescript

Typescript: Convert Enum to Array

Apr 22, 2023Abhishek EH2 Min Read
Typescript: Convert Enum to Array

Do you want to loop through the TypeScript enum? We will see how to convert different types of enum to an array in this article.

Iterating default enum

Consider the following enum:

1enum Direction {
2 Up,
3 Down,
4 Left,
5 Right,
6}

Let's print it and see what we get:

1console.log(Direction) // {"0":"Up","1":"Down","2":"Left","3":"Right","Up":0,"Down":1,"Left":2,"Right":3}

As you can see that both the keys and values are present twice, once as keys and once as values. This is present so that we can access it in both the ways Direction["0"] and Direction["Up"].

Now iterating them can be difficult.

We can either loop through keys or values. How do we identify if it is a key or value (in the enum)? We can check if it is a number or not as shown below:

1enum Direction {
2 Up,
3 Down,
4 Left,
5 Right,
6}
7
8console.log(Object.values(Direction).filter(v=>isNaN(v)) //["Up", "Down", "Left", "Right"]
9
10console.log(Object.values(Direction).filter(v=>!isNaN(v)) // [0, 1, 2, 3]

Iterating enum with specific values

Let's say our enum looks like this, now we cannot use the isNaN technique.

1enum Status {
2 Active = "A",
3 Inactive = "I",
4 Suspended = "S",
5}

Let's print the enum and see:

1console.log(Status) // {Active: "A", Inactive: "I", Suspended: "S"}

As you can see, they are represented like objects. So we can loop through the keys and values as shown below:

1enum Status {
2 Active = "A",
3 Inactive = "I",
4 Suspended = "S",
5}
6console.log(Object.keys(Status)) // ["Active", "Inactive", "Suspended"]
7console.log(Object.values(Status)) // ["A", "I", "S"]

If you have liked article, stay in touch with me by following me on twitter.

Leave a Comment

© 2023 CodingDeft.Com