John Cooper
John Cooper

Reputation: 7631

Getting correspoding enum key for the value passed

var StateValue = {   
Unknown: 0,   
AL: 1,    
AK: 2,    
AZ: 3,    
AR: 4,    
CA: 5,    
CO: 6,   
CT: 7,    
DE: 8,
},

Now if i pass 8 i need the value DE to be printed. How can i do this.

Upvotes: 1

Views: 7890

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163258

A faster and simpler approach is to use an array:

var StateValues = ['Unknown', 'AL', 'AK', 'AZ', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE'];
alert(StateValues[9]); //'DE'

If for some reason, you need to use your existing structure, try this:

function find_key_by_value(set, value) {
   for(var k in set) {
      if(set.hasOwnProperty(k)) {
         if(set[k] == value) {
            return k;
         }
      }
   }
   return undefined;
}

alert(find_key_by_value(StateValue, 8));

Upvotes: 9

Related Questions