Thursday, May 3, 2012

Javascript ::: Enumerating all properties of an object

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Objects#Defining_getters_and_setters

 

Enumerating all properties of an object

Starting with ECMAScript 5, there are three native ways to list/traverse object properties:
  • for...in loops
    This method traverses all enumerable properties of an object and its prototype chain
  • Object.keys(o)
    This method returns an array with all the own (not in the prototype chain) enumerable properties names ("keys") of an object o.
  • Object.getOwnPropertyNames(o)
    This method returns an array containing all own properties names (enumerable or not) of an object o.
In ECMAScript 5, there is no native way to list all properties of an object. However, this can be achieved with the following function:
  1. function listAllProperties(o){       
  2.     var objectToInspect;       
  3.     var result = [];  
  4.       
  5.     for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)){    
  6.         result = result.concat(Object.getOwnPropertyNames(objectToInspect));    
  7.     }  
  8.       
  9.     return result;   
  10. }  
This can be useful to reveal "hidden" properties (properties in the prototype chain which are not accessible through the object, because another property has the same name earlier in the prototype chain). Listing accessible properties only can easily be done by removing duplicates in the array.

No comments:

Post a Comment