0

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.

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

What's the purpose of the filter step?
Some properties may be repeated like toString or constructor so the filter step removes duplicates
Yes, but getOwnPropertyNames() should cover that, right?
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 Arrays
Agreed. But you already have code to go up the prototype chain.
0

Well, for debug you could use this:

console.log(yourObject);

Simple and fast. Both in node and in browser. : )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.