Getting object properties

2012-10-02

There are various ways of getting a set of properties of an object. I'd like to list them and explain what set they actually gather. Getting the list of properties is handy when you use an object as a hash and want to iterate over all the elements of that hash.

for-in


This is the old ES3 way of gathering properties from an object. The gist is for (var key in obj) arr.push(key);. This will gather all enumerable properties and includes inherited properties. It's as far as you'll get with ES3, although you can filter them down to be just own properties using hasOwnProperty. Inherited properties that are shadowed are only gathered once.

Object.keys


This is the ES5 way of getting all own enumerable properties on an object. It won't return you inherited properties (but you could use Object.getPrototypeOf and walk the chain yourself...)

Object.getOwnPropertyNames


This ES5 method will return you all the properties on object, including non-enumerables. This was impossible to properly do in ES3. It also won't work for inherited properties, but like above, you can use Object.getPrototypeOf and walk the chain yourself :)

Notes


Object.getPrototypeOf could be replaced by simply checking obj.__proto__, support varies but is getting stronger

Object.getOwnPropertyNames will still not return you the magic __proto__ property.