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 or 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,

Given an enum declaration

// Enum Constant Declaration with number value
export enum Weeks {
    MONDAY = 1,
    TUESDAY= 2,
    WEDNESDAY = 3,
    THURSDAY = 4,
    FRIDAY = 5,
    SATURDAY=6,
    SUNDAY=7,
}

and Result after 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" },
];

Convert Enum to Array of objects in JavaScript

ES8 introduced the Object.entries() & Object.values() methods which works in the latest browsers, and polyfill is required for support in older browsers. These methods works with Enum classes also.

  • Use ES8 Object.entries() method

    • 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.
// Array to store objects
const arrayObjects = [];
// Iterate key and values of an Enum
for (const [propertyKey, propertyValue] of Object.entries(Weeks)) {
  if (!Number.isNaN(Number(propertyKey))) {
    continue;
  }
  // add to an array
  arrayObjects.push({ id: propertyValue, name: propertyKey });
}
// Print array of objects
console.log(arrayObjects);
  • Use Object.values() method

This example convert the All the enum key and values into an array.

const values = Object.values(Weeks);
console.log(values); //  ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY", 1, 2, 3, 4, 5, 6, 7]

Summarize

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