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?

1

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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); }
});

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.