1

I'd like to iterate over the properties and functions of any kind of a javascript object(IDBKeyRange in this case).

I tried using the following code :-

 <script type="text/javascript"> var arr = Object.getOwnPropertyNames(IDBKeyRange.only(43)); for(var i=0;i<arr.length;i++) { document.write(arr[i]+"</br>"); } </script> 

However, it fails to show me a list of properties and methods -- what am I doing wrong?

2
  • Seems to work in jsfiddle: jsfiddle.net/WMHyG Commented Feb 6, 2013 at 14:26
  • Does IDBKeyRange.only(43) return an IDBKeyRange object? Commented Feb 6, 2013 at 14:26

2 Answers 2

3

Use a for-in loop:

for(var key in myObject){ console.log(key, ':', myObject[key]); } 
Sign up to request clarification or add additional context in comments.

Comments

0

Object.getOwnPropertyNames returns an array of keys, the property names of the Object.

You have to loop through the Array and refer to the Object:

var O=// an object instance; var A= Object.getOwnPropertyNames(O).map(function(itm){ try{ return itm+':'+O[itm]; } catch(er){ return itm+': ERROR!'+er.message; } }); alert(A.join('\n')); 

If any keys refer to objects you'll need a recursive method-

function deepProps(O){ var arr= Object.getOwnPropertyNames(O).map(function(itm){ var hoo= O[itm]; try{ if(hoo== window){ return '\n'+itm+': window'; } if(hoo){ if(hoo.nodeName) return itm+': '+ hoo.nodeName; if(typeof O[itm]== 'object'){ return '\n\n'+itm+':\n'+deepProps(O[itm]); } return itm+': '+O[itm]; } return itm+': null'; } catch(er){ return itm+': '+ 'ERROR! '+er.message; } }) return arr.join('\n'); } 

Comments