{

Multiple ways to Convert Enum to Array of objects in Typescript with examples


Typescript Convert Enum to Array

In this tutorial, you are about to learn multiple ways to convert enum to an array of objects, an array of strings, and an array of key and value pairs in typescript with examples.

Typescript enum

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

Most of the programming languages support enums. You can check more about Typescript enum

You can check my other posts on typescript Enum object.

Object contains key and value properties enclosed in {} and array is group of types enclosed in [].

Because Enum and array are different types of objects, and structure data We have to write a code to handle conversions to display in the drop-down on the UI element.

let’s declare and initialize enum in typescript

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

Following is the output after converting to an array of objects

[ { 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' } ] 

There are many ways we can do convert Enum to Array of objects in typescript,

How to convert Enum to Object Array using ES8 Object.entries?

In this example, the Enum key and values are converted to an array of object keys and values.

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

Object.entries() method returns the key and values by iterating an object. Notes:

  • Retrieve key 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.

Here is an example

  
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);  

Convert Enum values as String Array

Sometimes, We need to convert Enum values as an array, Object.values return key and values as seen in order below for the enum object.

console.log(Object.values(Weeks));

Output:

 ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY", 1, 2, 3, 4, 5, 6, 7] 

Another way is to pull only strings into an array using the below code with array filter and filters only string values.

const arrayValues = Object.values(Weeks).filter(value => typeof value === 'string')
console.log(arrayValues);

output:

["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"] 

Convert Enum values as Array key and value strings

In this example, Iterated an Enum object using for in loop and Construct the array and push the key and values as described below

let output = [];

for (let key in Weeks)
{
    output.push({name: key, number:Weeks[key] });    
}
console.log(res);

Output:

[{
  "name": "1",
  "number": "MONDAY"
}, {
  "name": "2",
  "number": "TUESDAY"
}, {
  "name": "3",
  "number": "WEDNESDAY"
}, {
  "name": "4",
  "number": "THURSDAY"
}, {
  "name": "5",
  "number": "FRIDAY"
}, {
  "name": "6",
  "number": "SATURDAY"
}, {
  "name": "7",
  "number": "SUNDAY"
}, {
  "name": "MONDAY",
  "number": 1
}, {
  "name": "TUESDAY",
  "number": 2
}, {
  "name": "WEDNESDAY",
  "number": 3
}, {
  "name": "THURSDAY",
  "number": 4
}, {
  "name": "FRIDAY",
  "number": 5
}, {
  "name": "SATURDAY",
  "number": 6
}, {
  "name": "SUNDAY",
  "number": 7
}] 

Summarize

To Sum up, you learned how to convert Enum to a typescript array object with examples.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.