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"?
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.
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.
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.
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.
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;
}
Using underscore.js:
_.invert(someHash)[value]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With