Search code examples
javascriptjqueryprototypejs

How can I get a key name (in a hash) by using its value?


I understand this is a little unorthodox.

Lets say I have this hash.

 someHash = {
    'item1' => '5',
    'item2' => '7',
    'item3' => '45',
    'item4' => '09'
}

Using native js, or prototype or Jquery -- is there a method that will enable me to get the "key name" by just having the value?

I don't want all the keys, just the one that matches my value. Sorta of a like a map in reverse?

I am getting a return from the db which I get a "value" and I have to match that value with some js hash on the front end.

So the app hands me "45"... Is there a way to use js (prototype or jquery) to then get the key "item3"?


Solution

  • In order to get the keys which map to a given value you'll need to search the object properties. For example

    function getKeysForValue(obj, value) {
      var all = [];
      for (var name in obj) {
        if (Object.hasOwnProperty(name) && obj[name] === value) {
          all.push(name);
        }
      }
      return all;
    }