Sunday, March 31, 2013

Javascript: Iterate over keys in an object.

How to loop through each key in an object. 

 var testObject = {  
   item1: "apple",  
   item2: "banana",  
   item3: "pear"  
 };  
   
 for (var thing in testObject){  
   var item = thing;  
   alert(item);  
 }  
 //alerts the keys  
   
 for (var thing in testObject){  
   var item = testObject[thing];  
   alert(item);  
 }  
 //alerts the value  

When the object contains objects.
 var testObject = {  
   "apple": {"weight": 20, "number": 5, "taste":"delicious"},  
   "banana": {"weight": 10, "number": 5, "taste":"delicious"},  
   "pear": {"weight": 50, "number": 5, "taste":"delicious"}  
 };  
   
 alert("alert the keys");  
 for (var key in testObject){  
   var temp = key;  
   alert(key);  
 }  
   
 alert("alert the sub keys");  
 for (var key in testObject){  
   var mainKey = testObject[key];  
   for (var subKey in mainKey){  
     var temp = subKey;  
     alert(temp);  
   }  
 }  
   
 alert("alert the sub values");  
 for (var key in testObject){  
   var mainKey = testObject[key];  
   for (var subKey in mainKey){  
     var temp = mainKey[subKey];  
     alert(temp);  
   }  
 }