Reputation: 44605
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?
Upvotes: 0
Views: 122
Reputation: 15882
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); }
});
Upvotes: 2
Reputation: 407
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.
Upvotes: 0
Reputation: 3798
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
Upvotes: 0
Reputation: 37177
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
Upvotes: 3