Is it possible to get the non-enumerable inherited property names of an object?

后端 未结 9 1871
温柔的废话
温柔的废话 2020-11-22 12:46

In JavaScript we have a few ways of getting the properties of an object, depending on what we want to get.

1) Object.keys(), which returns all own, enu

9条回答
  •  暖寄归人
    2020-11-22 13:40

    A cleaner solution using recursion:

    function getAllPropertyNames (obj) {
        const proto     = Object.getPrototypeOf(obj);
        const inherited = (proto) ? getAllPropertyNames(proto) : [];
        return [...new Set(Object.getOwnPropertyNames(obj).concat(inherited))];
    }
    

    Edit

    More generic functions:

    function walkProtoChain (obj, callback) {
        const proto     = Object.getPrototypeOf(obj);
        const inherited = (proto) ? walkProtoChain(proto, callback) : [];
        return [...new Set(callback(obj).concat(inherited))];
    }
    
    function getOwnNonEnumPropertyNames (obj) {
        return Object.getOwnPropertyNames(obj)
            .filter(p => !obj.propertyIsEnumerable(p));
    }
    
    function getAllPropertyNames (obj) {
        return walkProtoChain(obj, Object.getOwnPropertyNames);
    }
    
    function getAllEnumPropertyNames (obj) {
        return walkProtoChain(obj, Object.keys);
    }
    
    function getAllNonEnumPropertyNames (obj) {
        return walkProtoChain(obj, getOwnNonEnumPropertyNames);
    }
    

    This same template can be applied using Object.getOwnPropertySymbols, etc.

提交回复
热议问题