Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?

like image 883
james emanon Avatar asked Mar 14 '12 21:03

james emanon


People also ask

How do you check if a hash contains a key?

We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.

How do I get the hash key?

Simply pressing alt and 3 at the same time will insert a # hash symbol into your text in any application. This shortcut will work with all versions of Mac OS X whether you have a Macbook, Air or an iMac. In most cases Apple has decided to replace this key with a symbol of the local currency.

How get key from hash value in Perl?

Extracting Keys and Values from a Hash variable The list of all the keys from a hash is provided by the keys function, in the syntax: keys %hashname . The list of all the values from a hash is provided by the values function, in the syntax: values %hashname . Both the keys and values function return an array.

What is key and value in hash?

A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.


2 Answers

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;
}
like image 189
JaredPar Avatar answered Oct 12 '22 22:10

JaredPar


Using underscore.js:

_.invert(someHash)[value]
like image 35
Igor Drozdov Avatar answered Oct 12 '22 22:10

Igor Drozdov