Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript's equivalent of java's Map.getKey()

I have a map or say an associative array kind of structure in JavaScript:

var myMap = {"one": 1, "two": 2, "three": 3};

To get keys corresponding to a given value I have to iterate through the map:

function map_test(value) {
  var myMap = {"one": 1, "two": 2, "three": 3};   
  for (key in myMap) {
    if (myMap[key] == value) {
       alert(key);
       break;
    }
  }
}

Is there some function like Java's Map.getKey() or a better way of getting keys?

like image 656
hitesh israni Avatar asked Dec 22 '22 01:12

hitesh israni


2 Answers

var myMap = {"one": 1, "two": 2, "three": 3};

declare it as a global variable

function getKey(value){
    var flag=false;
    var keyVal;
    for (key in myMap){
         if (myMap[key] == value){
             flag=true;
             keyVal=key;
             break;
         }
    }
    if(flag){
         return keyVal;
    }
    else{
         return false;
    }
}

I dont think you need any function to get the value of a specific key.

You just have to write

var value = myMap[key];
like image 93
Tejasva Dhyani Avatar answered Jan 10 '23 21:01

Tejasva Dhyani


for your specific case there is a faster solution:

function map_test(key,value)
{
var myMap = {"one": 1, "two": 2, "three": 3};
if(myMap.hasOwnProperty(key)) alert(key);
}
map_test('two',2);

In general, there isn't a direct method getKeys()

like image 42
Luca Rainone Avatar answered Jan 10 '23 19:01

Luca Rainone