Search code examples
javascriptnode.jsecmascript-5

Getting all the properties of an object in JavaScript


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.


Solution

  • 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;
    }