How can I get a key name (in a hash) by using its value?
Solution 1
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;
}
Solution 2
Using underscore.js:
_.invert(someHash)[value]
Solution 3
There is no direct method but you can try something like this.
var key;
$.each(someHash, function(key, val){
if(val == 'valToCompare'){
key = key;
return false;
}
});
Solution 4
Without uniqueness you can get the first:
var hash = {item1: 0, item2: 1},
value = 1,
key;
for(var i in hash)
{
if (hash.hasOwnProperty(i) && hash[i] === value) {
key = i;
break;
}
}
key; // item2
hasOwnProperty
ensures that hash has the property not a prototype.
break
stops the loop once a key is found.
Solution 5
I don't know of a native answer, but you could write your own:
var someHash = {
'item1' : '5',
'item2' : '7',
'item3' : '45',
'item4' : '09'
};
function getKeyByValue(hash, value) {
var key;
for(key in hash) {
if (hash[key] == value) return key;
}
}
alert(getKeyByValue(someHash, '7'));
james emanon
Updated on July 16, 2022Comments
-
james emanon almost 2 years
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"?