Typescript example - Convert Enum to Array of objects


Enum is new data type introduced in typescript. It’s data is of set of constants. Data in enums of Strings and numbers.

Object is key and value properties enclosed in {} and array is group of types enclosed in []. Enum and array of objects are of different types and structure, We have to write a code to handle conversions to display in drop-down on UI element.
There are many ways we can 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 convert to 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 Object.entries() method which works in latest browsers, polyfill is required for support in older browsers.

  • Retrieve key and values using Object.entries() method. 
  • Use for-of loop to iterate the each element of enum data.
  • Check for key value of numers and ignore id of strings.
  • Add the array of keys and values to newly created array using 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);  

Similar Posts