-2

I have this enum:

export enum myEnum {
  name1 = 'my name',
  name2 = 'my other name',
  name3 = 'other'
}

and i have a myEnum object:

const x = myEnum.name1;
console.log(x)  // prints 'my name' 

How can i print 'name1' with my const x? In other words, how to get the enum name 'name1' with a myEnum value 'myEnum.name1'?

EDIT:

This is how it looks:

enter image description here

enter image description here

akcasoy
  • 6,497
  • 13
  • 56
  • 100
  • 2
    I don't understand the use case here, and how this will be useful? – Harry Mar 11 '20 at 10:09
  • 1
    Does this answer your question? [Reverse-Mapping for String Enums](https://stackoverflow.com/questions/44883072/reverse-mapping-for-string-enums) – Yury Tarabanko Mar 11 '20 at 10:10
  • @YuryTarabanko unfortunately not. – akcasoy Mar 11 '20 at 10:26
  • @Harry it is actually very useful and a very simple use case which u have more or less in every other language. getting the name of enum with its value. what is so weird about it? Java for example does have a method "name()" for its enums exactly for this purpose. – akcasoy Mar 11 '20 at 10:31
  • Can you give an an example of such a use case? I am trying to understand and learn :) – Harry Mar 11 '20 at 10:34
  • @Harry one of our endpoints use the same enum, but with different values.. so i have to call this endpoint with the "name" of this enum. so in post request's body you see sth like "{selectedMyEnum: "name1"}" – akcasoy Mar 11 '20 at 11:37
  • ok I get you @akcasoy – Harry Mar 11 '20 at 12:11
  • You can create "reverse enum": https://www.typescriptlang.org/play/#code/KYOwrgtgBBCeCi5oG8CwAoKUQEMLAEYoBeKAcjmz2DIBoMtd8AmE8ygewBcALYAJyr46DIcADMbMtz78yGAL4YMAYw4gAzlyj9gANwEbgAWQRI2AeQBGAK2AquAOlBd+AS2AaAFHESQAlI66ACZgKsBeXvy0UADaANbAsDF6OAA2YMAAuv4kAHxQaJg6sakZ2WyJsADcorpcYPwgOrXoCjHICv6tquoaHGnAjmkcAOZR+oYmZgFAA – Aleksey L. Mar 11 '20 at 14:10

1 Answers1

0

As per the documentation, enums can be reverse-mapped as follows:

enum Enum {
    A
}
let a = Enum.A;
let nameOfA = Enum[a]; // "A"

To enumerate the values and keys of the enum, it can effectively be treated as a standard JS object. Here, you might choose to probe it with Object.entries:

Object.entries(myEnum)

will yield an array of key-value pairs:

[["name1","my name"],["name2","my other name"],["name3","other"]]
spender
  • 117,338
  • 33
  • 229
  • 351
  • 1
    this is the case when an enum does not have a value. but in my case this does not work. Enum[Enum.A] (where A actually has a value like "value"), does not give you the "A" – akcasoy Mar 11 '20 at 10:04