-1

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
}


1 Answers1

1

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);
Rayon
  • 36,219
  • 4
  • 49
  • 76
vaira
  • 2,191
  • 1
  • 10
  • 15
  • yep, I already do that, get key:value pair object from array, but I want to know, is there any possibility to get enum from object or build enum dynamically – Gevorg Martirosyan Nov 01 '22 at 08:36
  • 1
    @GevorgMartirosyan Doesn't "_No you can not get an enum, which is a pre-defined type_" answer your question? TypeScript is compiled into JavaScript. At runtime (which is where the "dynamic" code runs), enums don't exist. But this feels like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Ivar Nov 01 '22 at 08:40
  • yeah, you already answer, thank you a lot! – Gevorg Martirosyan Nov 01 '22 at 08:43