0

I have the following javascript variable:

var myList =
    {
        itemA: 0,
        itemB: 1,
        itemC: 2,
        itemD: 3,
        itemE: 4
    };

I have the value of the variable, ie 0, 1, 2 etc and need to find the corresponding key to it ie if I have 2, the key would be itemC.

How can I do this with javascript?

amateur
  • 43,371
  • 65
  • 192
  • 320

4 Answers4

3

You'd have to iterate over every property until you find the one with that value.

for(var prop in myList) 
    if(myList[prop] == value)
       return prop;
return NOT_FOUND; // or whatever
Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
2

You can try this: http://jsfiddle.net/shaneburgess/7DzUM/

    var myList =
    {
        itemA: 0,
        itemB: 1,
        itemC: 2,
        itemD: 3,
        itemE: 4
    };

$.each(myList,function(index,value){
    if(value == 2){ alert(index); }
});
shaneburgess
  • 15,702
  • 15
  • 47
  • 66
0

if u write this like this:

 var myList =
    {
    "itemA": "0",
    "itemB": "1",
    "itemC": "2",
    "itemD": "3",
    "itemE": "4"
};

it will be a json object. then u can get itemC like this myList.itemC

Sedat Başar
  • 3,740
  • 3
  • 25
  • 28
0

You can also loop through using the .each jQuery function if you want a pure jQuery solution. http://api.jquery.com/jQuery.each/ However, isbadawi's method would work well also.

Nolan St. Martin
  • 407
  • 1
  • 3
  • 16