Object from enum typescript

Object from enum typescript

Last updated: Jan 20, 2023
Reading time · 6 min

banner

# Table of Contents

If you need to get the length of an Enum, click on the following subheading:

# Get Enum values as an Array in TypeScript

To get all enum values as an array, pass the enum to the Object.values() method.

The Object.values method will return an array of the enum’s values because enums in TypeScript are real objects and exist at runtime.

Copied!
// ✅ For STRING Enums enum StringEnum Small = 'S', Medium = 'M', Large = 'L', > const values = Object.values(StringEnum); // 👇️ ['S', 'M', 'L'] console.log(values); const names = Object.keys(StringEnum); // 👇️ ['Small', 'Medium', 'Large'] console.log(names);

If you have a numeric enum, use the following code sample instead.

Copied!
// ✅ For NUMERIC Enums enum NumericEnum Small, Medium, Large, > const values = Object.keys(NumericEnum).filter((v) => !isNaN(Number(v))); console.log(values); // 👉️ ['0', '1', '2'] const names = Object.keys(NumericEnum).filter((v) => isNaN(Number(v))); console.log(names); // 👉️ ['Small', 'Medium', 'Large']

Enums are real objects in TypeScript and exist at runtime. This is why we are able to use the Object.values method to get an array containing the enum’s values.

The Object.values() method returns an array containing an object’s values.

Copied!
// 👇️ ['bobby hadz', 30] console.log(Object.values( name: 'bobby hadz', age: 30 >));

However, the output for numeric and string enums is different.

Copied!
// ✅ For STRING Enums enum StringEnum Small = 'S', Medium = 'M', Large = 'L', > // 👇️ ['S', 'M', 'L'] console.log(Object.values(StringEnum)); // ✅ For NUMERIC Enums enum NumericEnum Small, Medium, Large, > // 👇️ ['Small', 'Medium', 'Large', 0, 1, 2] console.log(Object.values(NumericEnum));

Notice that when a numeric enum is passed to the Object.values() method, the enum’s keys and values are returned.

We haven’t provided an initial value for the numeric enum, so its values start at 0 and auto-increment.

This is why we had to filter out the unnecessary keys in the examples.

Want to learn more about working with Enums in TypeScript ? Check out these resources: How to Iterate over Enums in TypeScript ,Check if a Value exists in an Enum in TypeScript.

# Get all Enum Names as an Array in TypeScript

If you need to get all enum names as an array:

  1. Pass the enum as a parameter to the Object.keys() method.
  2. If the enum is numeric, filter the enum values out of the array.
  3. For string enums, the Object.keys() method returns an array containing the enum names.
Copied!
// ✅ STRING Enums enum StringEnum Yes = 'Y', No = 'N', Maybe = 'M', > const names = Object.keys(StringEnum); console.log(names); // 👉️ ['Yes', 'No', 'Maybe']

If you have a numeric enum, use the Array.filter() method.

Copied!
// ✅ NUMERIC Enums enum NumericEnum Yes, No, Maybe, > const names = Object.keys(NumericEnum).filter((v) => isNaN(Number(v))); console.log(names); // 👉️ ['Yes', 'No', 'Maybe']

Enums in TypeScript are real objects and exist at runtime, so we are able to pass an enum to the Object.keys method.

The Object.keys() method returns an array containing the object’s keys.

Copied!
// 👇️ ['name', 'age'] console.log(Object.keys( name: 'bobby hadz', age: 30 >));

However, the output for numeric and string enums is different.

Copied!
// ✅ NUMERIC Enums enum NumericEnum Yes, No, Maybe, > // ✅ STRING Enums enum StringEnum Yes = 'Y', No = 'N', Maybe = 'M', > // 👇️ ['0', '1', '2', 'Yes', 'No', 'Maybe'] console.log(Object.keys(NumericEnum)); // 👇️ ['Yes', 'No', 'Maybe'] console.log(Object.keys(StringEnum));

Notice that when a numeric enum is passed to the Object.keys method, we get an array containing the values and the names of the enum, whereas, for a string enum, we only get the names.

This is why we used the filter() method — to filter out the enum values from the array.

If you need to iterate over enums, check out the following article.

The examples above wouldn’t work if you use const enums because const enums can only use constant enum expressions and are completely removed during compilation.

# Convert an Enum to an Array of Objects in TypeScript

To convert an enum to an array of objects:

  1. Use the Object.keys() method to get an array of the enum’s keys.
  2. Filter out the unnecessary values for numeric enums.
  3. Use the map() method to iterate over the array, returning an object on each iteration.
Copied!
// ✅ For NUMERIC Enums enum NumericEnum Small, Medium, Large, > const arr = Object.keys(NumericEnum) .filter((v) => isNaN(Number(v))) .map((name) => return id: NumericEnum[name as keyof typeof NumericEnum], name, >; >); // 👇️ [, , ] console.log(arr);

If you have a string enum, use the following code sample instead.

Copied!
// ✅ For STRING Enums enum StringEnum Small = 'S', Medium = 'M', Large = 'L', > const arr = Object.keys(StringEnum).map((name) => return name, value: StringEnum[name as keyof typeof StringEnum], >; >); // 👇️ [, , ] console.log(arr);

The code sample shows how to convert numeric and string enums to an array of objects.

Enums in TypeScript are real objects and exist at runtime, so we are able to use the Object.keys method to get an array of the enum’s keys.

Copied!
// ✅ For NUMERIC Enums enum NumericEnum Small, Medium, Large, > // 👇️ ['0', '1', '2', 'Small', 'Medium', 'Large'] console.log(Object.keys(NumericEnum)); // ✅ For STRING Enums enum StringEnum Small = 'S', Medium = 'M', Large = 'L', > // 👇️ ['Small', 'Medium', 'Large'] console.log(Object.keys(StringEnum));

The output for numeric enums includes the values, so we had to use the filter() method to filter out any of the unnecessary values from the array.

The last step is to use the Array.map method to loop over the array of enum names and return an object containing the name and value on each iteration.

We used keyof typeof in the examples to cast the string to an enum, so we can access the corresponding value.

Copied!
// ✅ For STRING Enums enum StringEnum Small = 'S', Medium = 'M', Large = 'L', > const arr = Object.keys(StringEnum).map((name) => return name, value: StringEnum[name as keyof typeof StringEnum], >; >); // 👇️ [, , ] console.log(arr);

The Array.map() method returns an array of objects where each object has 2 key-value pairs — the name of the enum member and the corresponding value.

# Get the length of an Enum in TypeScript

To get the length of an enum:

  1. Use the Object.keys() method to get an array containing the enum’s keys.
  2. Access the length property on the array.
  3. When working with numeric enums, divide the result by 2 , because a reverse mapping is generated.
Copied!
// ✅ For String Enums enum Sizes Small = 'S', Medium = 'M', Large = 'L', > const len = Object.keys(Sizes).length; console.log(len); // 👉️ 3

# Get the length of a Numeric enum in TypeScript

If you work with numeric enums, use the following code sample instead.

Copied!
// ✅ For Numeric Enums enum SizesNumeric Small, Medium, Large, > const len = Object.keys(SizesNumeric).length / 2; console.log(len); // 👉️ 3

If your enum contains both string and numeric values, use the following code sample.

Copied!
// ✅ For Mixed Enums (both strings and numbers) enum SizesMixed Small = 1, Medium = 'test', Large = 3, ExtraLarge = 4, > const len = Object.keys(SizesMixed).filter((v) => isNaN(Number(v))).length; console.log(len); // 👉️ 4

Enums in TypeScript are real objects and exist at runtime. This is why we are able to pass an enum to the Object.keys method.

The Object.keys() method returns an array containing the object’s keys.

Copied!
// 👇️ ['name', 'age'] console.log(Object.keys( name: 'Bobby hadz', age: 30 >));

However, the output for numeric and string enums is different.

Copied!
// ✅ For String Enums enum Sizes Small = 'S', Medium = 'M', Large = 'L', > // 👇️ ['Small', 'Medium', 'Large'] console.log(Object.keys(Sizes)); // ✅ For Numeric Enums enum SizesNumeric Small, Medium, Large, > // 👇️ ['0', '1', '2', 'Small', 'Medium', 'Large'] console.log(Object.keys(SizesNumeric));

Notice that when a numeric enum is passed to the Object.keys method, we get an array containing the values and the names of the enum, whereas, for a string enum, we only get the names.

This is because a reverse mapping gets generated only for numeric enums.

The reverse mapping allows us to access a numeric enum’s key by a value.

Copied!
// ✅ For Numeric Enums enum SizesNumeric Small, Medium, Large, > console.log(SizesNumeric[0]); // 👉️ "Small" console.log(SizesNumeric[1]); // 👉️ "Medium"

This is why we had to divide the length of the array we got from the Object.keys() method by 2 for numeric enums.

Copied!
// ✅ For Numeric Enums enum SizesNumeric Small, Medium, Large, > const len = Object.keys(SizesNumeric).length / 2; console.log(len); // 👉️ 3

String enum members don’t get a reverse mapping generated at all.

# Get the length of a Mixed Enum in TypeScript

If you work with mixed enums (ones that contain both string and numeric members), you have to filter out the keys for the reverse mapping.

In other words, we have to exclude the valid numbers from the array of keys.

Copied!
// ✅ For Mixed Enums (both strings and numbers) enum SizesMixed Small = 1, Medium = 'M', Large = 3, ExtraLarge = 4, > const length3 = Object.keys(SizesMixed).filter((v) => isNaN(Number(v))).length; console.log(length3); // 👉️ 4

The filter() method is there to filter out all of the keys in the array that are valid numbers (the generated reverse mapping keys).

We don’t have to divide by 2 because we’ve already excluded all of the keys that were generated for the reverse mappings.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Php функция проверки url
Оцените статью