Bridging the Gap: Exploring Methods to Convert TypeScript Enums to JavaScript Object Arrays
- Enums (Enumerations): In TypeScript, enums are special kinds of objects that define a set of named constants. These constants typically represent a fixed number of choices or options. For example:
enum Color {
Red,
Green,
Blue
}
Here, Color.Red
, Color.Green
, and Color.Blue
are the constants representing different colors.
- Object Arrays: An object array is an array where each element is an object. These objects can have properties (key-value pairs) to hold additional information.
Conversion Process:
TypeScript enums are compiled down to JavaScript objects at runtime. This allows you to leverage JavaScript's built-in methods to extract the enum's data and create an object array. Here are two common approaches:
Using Object.entries():
The Object.entries()
method returns an array of key-value pairs from an object. We can use this to get both the enum member names (keys) and their corresponding numerical values:
enum Color {
Red = 0,
Green = 1,
Blue = 2
}
function enumToObjectArray(enumObj: any): { name: string; value: number }[] {
const entries = Object.entries(enumObj);
return entries.map(([key, value]) => ({ name: key, value }));
}
const colorArray = enumToObjectArray(Color);
console.log(colorArray); // Output: [{ name: "Red", value: 0 }, { name: "Green", value: 1 }, { name: "Blue", value: 2 }]
Explanation:
- We define a
enumToObjectArray
function that takes an enum object (enumObj
) as input. - We use
Object.entries(enumObj)
to get an array of key-value pairs from the enum. - We use the
map()
method to iterate over the entries and create a new array of objects. - Inside the
map
callback, we destructure each entry intokey
andvalue
. - We return an object with properties
name
(set to the enum member name) andvalue
(set to the enum member's numerical value). - We call
enumToObjectArray
with theColor
enum and store the resulting object array incolorArray
.
Using Object.keys() and Object.values() (for simpler Enums):
- If your enum only has string or numeric values (without custom initialization), you can use
Object.keys()
to get the enum member names (keys) andObject.values()
to get the corresponding values:
enum Color {
Red,
Green,
Blue
}
function enumToObjectArraySimple(enumObj: any): { name: string }[] {
const keys = Object.keys(enumObj);
return keys.map(key => ({ name: key }));
}
const colorArraySimple = enumToObjectArraySimple(Color);
console.log(colorArraySimple); // Output: [{ name: "Red" }, { name: "Green" }, { name: "Blue" }]
- This approach assumes simpler enums with string or numeric values.
- We use
Object.keys(enumObj)
to get an array of enum member names. - Inside the
map
callback, we create an object with aname
property set to the current key.
Choosing the Right Approach:
- Use
Object.entries()
if you need both the enum member names and their numerical values in the object array. - Use
Object.keys()
andObject.values()
for simpler enums where you only need the names.
enum Color {
Red = 0,
Green = 1,
Blue = 2
}
function enumToObjectArray(enumObj: any): { name: string; value: number }[] {
const entries = Object.entries(enumObj);
return entries.map(([key, value]) => ({ name: key, value }));
}
const colorArray = enumToObjectArray(Color);
console.log(colorArray); // Output: [{ name: "Red", value: 0 }, { name: "Green", value: 1 }, { name: "Blue", value: 2 }]
- We define a
Color
enum with numerical values assigned to each member. Object.entries(enumObj)
gets an array of key-value pairs (member names and values).
enum Size {
Small,
Medium,
Large
}
function enumToObjectArraySimple(enumObj: any): { name: string }[] {
const keys = Object.keys(enumObj);
return keys.map(key => ({ name: key }));
}
const sizeArraySimple = enumToObjectArraySimple(Size);
console.log(sizeArraySimple); // Output: [{ name: "Small" }, { name: "Medium" }, { name: "Large" }]
- We define a
Size
enum with string values (assuming a simpler case). Object.keys(enumObj)
gets an array of enum member names (the string values).
Key Points:
- The first approach (
Object.entries()
) is more versatile as it captures both names and values. - The second approach (
Object.keys()
andObject.values()
) is simpler but only works for enums with string or numeric values (without custom initialization). - Remember to adapt the code based on your specific enum structure and the information you need in the object array.
This method iterates directly over the enum object's properties using a for...in
loop. It's a more basic approach but provides more control over the conversion process.
enum ShippingStatus {
Pending,
Shipped,
Delivered
}
function enumToObjectArrayForLoop(enumObj: any): { name: string; value: number }[] {
const result: { name: string; value: number }[] = [];
for (const key in enumObj) {
if (isNaN(Number(key))) continue; // Skip non-numeric keys (added for safety)
result.push({ name: key, value: enumObj[key] });
}
return result;
}
const shippingArray = enumToObjectArrayForLoop(ShippingStatus);
console.log(shippingArray); // Output: [{ name: "Pending", value: 0 }, { name: "Shipped", value: 1 }, { name: "Delivered", value: 2 }]
- We define a
ShippingStatus
enum. - We create an empty array (
result
) to store the objects. - We iterate over the
enumObj
properties using afor...in
loop. - Inside the loop, we check if the current key is a number using
isNaN(Number(key))
. This is because TypeScript might add non-numeric properties during compilation (like for reverse lookup). You can remove this check if you're confident your enum only has numeric values. - If the key is numeric (represents an enum member), we push an object with
name
(set to the key) andvalue
(set to the corresponding enum value) to theresult
array. - We return the
result
array containing the objects.
Using a custom helper function (for complex object structures):
If you need to create a more complex object structure from the enum data, you can define a custom helper function that takes the enum member name and value as arguments and constructs the desired object.
enum UserRole {
Admin = "administrator",
Editor = "content-editor",
Reader = "reader"
}
function enumToObjectArrayCustom(enumObj: any): { role: string; permissionLevel: number }[] {
const result: { role: string; permissionLevel: number }[] = [];
for (const key in enumObj) {
if (isNaN(Number(key))) continue;
const permissionLevel = key === "Admin" ? 3 : key === "Editor" ? 2 : 1;
result.push({ role: enumObj[key], permissionLevel });
}
return result;
}
const userArray = enumToObjectArrayCustom(UserRole);
console.log(userArray); // Output: [{ role: "administrator", permissionLevel: 3 }, { role: "content-editor", permissionLevel: 2 }, { role: "reader", permissionLevel: 1 }]
- We define a
UserRole
enum with custom string values. - We iterate over the
enumObj
properties using afor...in
loop (with the same safety check for non-numeric keys). - Inside the loop, we define a
permissionLevel
based on the current key (assuming a mapping between roles and permission levels). - We push an object with
role
(set to the enum value) andpermissionLevel
to theresult
array.
javascript arrays typescript