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

后端 未结 9 1907
温柔的废话
温柔的废话 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:29

    Here is the solution that I came up with while studying the subject. To get all non-enumerable non-own properties of the obj object do getProperties(obj, "nonown", "nonenum");

    function getProperties(obj, type, enumerability) {
    /**
     * Return array of object properties
     * @param {String} type - Property type. Can be "own", "nonown" or "both"
     * @param {String} enumerability - Property enumerability. Can be "enum", 
     * "nonenum" or "both"
     * @returns {String|Array} Array of properties
     */
        var props = Object.create(null);  // Dictionary
    
        var firstIteration = true;
    
        do {
            var allProps = Object.getOwnPropertyNames(obj);
            var enumProps = Object.keys(obj);
            var nonenumProps = allProps.filter(x => !(new Set(enumProps)).has(x));
    
            enumProps.forEach(function(prop) {
                if (!(prop in props)) {
                    props[prop] = { own: firstIteration, enum_: true };
                }           
            });
    
            nonenumProps.forEach(function(prop) {
                if (!(prop in props)) {
                    props[prop] = { own: firstIteration, enum_: false };
                }           
            });
    
            firstIteration = false;
        } while (obj = Object.getPrototypeOf(obj));
    
        for (prop in props) {
            if (type == "own" && props[prop]["own"] == false) {
                delete props[prop];
                continue;
            }
            if (type == "nonown" && props[prop]["own"] == true) {
                delete props[prop];
                continue;
            }
    
            if (enumerability == "enum" && props[prop]["enum_"] == false) {
                delete props[prop];
                continue;
            }
            if (enumerability == "nonenum" && props[prop]["enum_"] == true) {
                delete props[prop];
            }
        }
    
        return Object.keys(props);
    }
    

提交回复
热议问题