How to Convert Enum to Array of objects in Typescript?

Enum is a new data type introduced in typescript. Its data is a group of constants. Data in the enum object are of String and number type.

You can check my other posts on typescript Enum object.

The object is key and value properties are enclosed in and the array is a group of types enclosed in [].

Enum and array of objects are of different types and structures, We have to write a code to handle conversions to display in the drop-down on the UI element.
There are many ways we can do convert Enum to Array of objects,

But I am going to use ES8 Object.entries .

Given an enum declaration

export enum Weeks {
    MONDAY = 1,
    TUESDAY= 2,
    WEDNESDAY = 3,
    THURSDAY = 4,
    FRIDAY = 5,
    SATURDAY=6,
    SUNDAY=7,
}

and This post talks about converting to an array of objects as below

[
  { 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" },
];

ES8 Object.entries in JavaScript

ES8 introduced the Object. entries() method which works in the latest browsers, and polyfill is required for support in older browsers.

  • Retrieve keys and values using Object.entries() method.
  • Use the for-of loop to iterate each element of enum data.
  • Check for the key value of numbers and ignore the id of strings.
  • Add the array of keys and values to the newly created array using the push method.
const arrayObjects = [];

for (const [propertyKey, propertyValue] of Object.entries(Weeks)) {
  if (!Number.isNaN(Number(propertyKey))) {
    continue;
  }
  arrayObjects.push({ id: propertyValue, name: propertyKey });
}

console.log(arrayObjects);

Summarize

In this post, you learned how to convert Enum to a typescript array with an example