Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to create enum from object, or build enum dynamically with forEach in typescript?

I want to get a enum from object, in typescript, is it possible? Example below!



const keys = ['a', 'b', 'c', 'd', 'e']
const values = [1, 2, 3, 4, 5]


// expected result
enum result {
  a = 1,
  b = 2,
  c = 3,
  d = 4,
  e = 5
}


>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

No you can not get an enum, which is a pre-defined type.

What you are trying to get is a mapping between the two arrays (dictionary/object), you can create it dynamically if they are always in the correct order.

const keys = ['a', 'b', 'c', 'd', 'e']
const values = [1, 2, 3, 4, 5]

// mapping
let dictionary  =  {};
keys.forEach((key, i)  => dictionary[key] = values[i]);
console.log(dictionary);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading