ArticleZip > Typescript Enum To Object Array

Typescript Enum To Object Array

TypeScript Enum to Object Array

Enum in TypeScript is a powerful data type that allows you to define a set of named constants. One common use case is to convert an enum into an array of objects, which can be beneficial for various scenarios like populating dropdown menus or displaying data in a structured format.

To convert a TypeScript enum into an array of objects, you can follow a few simple steps. Let's walk through the process.

First, define your enum in TypeScript. For example, let's consider an enum that represents different roles in a system:

Typescript

enum UserRole {
  Admin = 'ADMIN',
  Moderator = 'MODERATOR',
  User = 'USER',
}

Next, create a function that converts this enum into an array of objects. Here's a sample function that accomplishes this:

Typescript

function enumToObjectArray(enumObject: any) {
  return Object.keys(enumObject)
    .filter(key => isNaN(Number(enumObject[key])))
    .map(key => ({ id: enumObject[key], name: key }));
}

In this function:
1. We use Object.keys(enumObject) to get an array of keys from the enum.
2. We then filter out any keys that are numeric values using isNaN(Number(enumObject[key])) to avoid including any auto-generated enum properties.
3. Finally, we map each key to an object with the desired properties (in this case, id and name).

Now, you can call this function with your enum and get the desired array of objects:

Typescript

const userRolesArray = enumToObjectArray(UserRole);
console.log(userRolesArray);

By running this code, you will see an array of objects representing each enum member:

Typescript

[
  { id: 'ADMIN', name: 'Admin' },
  { id: 'MODERATOR', name: 'Moderator' },
  { id: 'USER', name: 'User' }
]

This resulting array of objects can then be used in your application to populate dropdowns, display data, or perform any other necessary operations.

Remember, when converting enums to object arrays, be mindful of the properties you want to include in each object and adjust the conversion function accordingly. Additionally, this approach provides a flexible way to work with enums and make them more versatile in your TypeScript projects.

In conclusion, converting a TypeScript enum to an object array is a handy technique that can enhance the usability of enums in your applications. By following the steps outlined above and customizing the conversion function to suit your needs, you can efficiently work with enum data in a structured and organized manner.

×