Alex Guerin
Alex Guerin

Reputation: 2386

Javascript: finding a value from an object

I have the following object:

var stuff = {}; 
stuff["jar"] = "biscuit"; 
stuff["cupboard"] = "food"; 

Iterating through the list with an For i loop and getting the value is easy, but how would I get the key?

for (var i in stuff) {  
    var key = GET KEY SOMEHOW 
    var val = stuff[i];   
}  

Upvotes: 0

Views: 54

Answers (4)

typedefcoder2
typedefcoder2

Reputation: 300

If you have the value already you may find the key by using this logic :

for (var i=0;i<numKeyValuePairs;i++)
{
if(val==key[i])
{
document.write(key[i];
}
}

Upvotes: 0

Ming-Tang
Ming-Tang

Reputation: 17651

The key is i. However, make sure that the key is in your object, not part of the prototype chain.

for (var i in stuff) {
  var key = i;
  if (stuff.hasOwnProperty(i)) {
    var val = stuff[i];   
  }
}  

See also:

Upvotes: 3

Francis Avila
Francis Avila

Reputation: 31631

You already have it:

for (var key in stuff) {
    var val = stuff[key];
}

Upvotes: 0

Stanley Stuart
Stanley Stuart

Reputation: 1145

var key = i;

In Javascript's for (foo in bar) if foo is the index of an object or array and happens to be a string, it should print or assign the string when called.

Upvotes: 0

Related Questions