How to get a key name (in a hash) using its value?

I understand that this is a little unorthodox.

Suppose I have this hash.

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

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

I do not need all the keys, only those that match my value. Varieties look like a map in the opposite direction?

I get a return from db that gets a β€œvalue”, and I need to match this value with some js hash on the front end.

So, the application passes me β€œ45” ... Is there a way to use js (prototype or jquery) to get the key β€œitem3”?

+6
source share
8 answers

To get keys that map to a given value, you will need to look for the properties of the object. for instance

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

Using underscore.js:

 _.invert(someHash)[value] 
+4
source

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; } }); 
+2
source

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 the hash does not have a prototype property.

break stops the loop after the key is detected.

+2
source

I do not know my own answer, but you can 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')); 
+2
source

Perhaps array_flip can help you. This creates a new array where the keys are values ​​and vice versa. Then just find the key in this new array, and the resulting value is the key in the original array that you were looking for.

0
source

Scroll through an object.

 function findInObj(obj, needle) for(var x in obj){ if(obj.x==needle) return x; } return false; } 
0
source

Since more than one property in an object can have the same value, you can return an array of property names corresponding to the value.

 var someHash={ 'item1':'5', 'item2':'7', 'item3':'45', 'item4':'09', 'item5':'7' } function hasAny(what){ var names= []; for(var p in this){ if(this[p]=== what) names.push(p); } return names; } 

hasAny.call (someHash, '7');

/ * return value: (array) item2, Item5 * /

0
source

Source: https://habr.com/ru/post/910746/


All Articles