Does JavaScript have a way to get all the properties of an object, including the built-in ones? for... in skips built-in properties, which is usually what you want, but not in this case. I'm using Node.js if that matters, and it's for debugging purposes so it doesn't have to be elegant, fast or portable.
Add a comment
|
2 Answers
Yeah it does, just go up through the prototype and get all properties
function getAllProperties(o) {
var properties = [];
while (o) {
[].push.apply(properties, Object.getOwnPropertyNames(o))
o = Object.getPrototypeOf(o);
}
//remove duplicate properties
properties = properties.filter(function(value, index) {
return properties.indexOf(value) == index;
})
return properties;
}
5 Comments
user949300
What's the purpose of the filter step?
openorclose
Some properties may be repeated like toString or constructor so the filter step removes duplicates
user949300
Yes, but
getOwnPropertyNames() should cover that, right?openorclose
No,
getOwnPropertyNames only returns an array of "direct" properties of the object and not those of its prototype (Object.getOwnPropertyNames([]) just returns ['length']). So to get all the properties of the object we have to go up the prototype chain and get their properties as well. And along the way some properties get overridden such as toString for Arraysuser949300
Agreed. But you already have code to go up the prototype chain.