2

It has been quite sometime when I explored different ways of implementing Enums in javaScript

say I have an Enum names as Mediumas

    Medium : {
            ONLINE : {id: 1, desc: "Online"},
            CREDIT : {id: 2, desc: "Credit Card"},
            DEBIT : {id: 3, desc: "Debit Card"},
            NETBANKING : {id: 4, desc: "Net Banking"}
   }

say I got an information that medium is 3. Now from this information how can I get the details like description. In this case it should return "Debit card".

Searched a lot on internet but not able to get any lead.

Geek_To_Learn
  • 1,536
  • 3
  • 19
  • 36

2 Answers2

1

try with Array#find method

var   PaymentMedium ={
            ONLINE : {id: 1, desc: "Online"},
            CREDIT : {id: 2, desc: "Credit Card"},
            DEBIT : {id: 3, desc: "Debit Card"},
            NETBANKING : {id: 4, desc: "Net Banking"}
   }
   
   function get(id){
   return Object.values(PaymentMedium).find(a=> (a.id == id)).desc
   }
   console.log(get(3))
prasanth
  • 19,775
  • 3
  • 25
  • 48
0

The order of properties in a JavaScript objects aren't guaranteed, so you'd need to use an array if you want to specify the position. See this S.O question.

Alternatively, you could get the required property by using the id value within it? (See Prasad's answer above)

WheretheresaWill
  • 4,952
  • 4
  • 27
  • 42