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

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

    Straight forward iterative in ES6:

    function getAllPropertyNames(obj) {
        let result = new Set();
        while (obj) {
            Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
            obj = Object.getPrototypeOf(obj);
        }
        return [...result];
    }
    

    Example run:

    function getAllPropertyNames(obj) {
      let result = new Set();
      while (obj) {
        Object.getOwnPropertyNames(obj).forEach(p => result.add(p));
        obj = Object.getPrototypeOf(obj);
      }
      return [...result];
    }
    
    let obj = {
      abc: 123,
      xyz: 1.234,
      foobar: "hello"
    };
    
    console.log(getAllPropertyNames(obj));

    0 讨论(0)
  • 2020-11-22 13:42

    Taking advantage of Sets leads to a somewhat cleaner solution, IMO.

    const own = Object.getOwnPropertyNames;
    const proto = Object.getPrototypeOf;
    
    function getAllPropertyNames(obj) {
        const props = new Set();
        do own(obj).forEach(p => props.add(p)); while (obj = proto(obj));
        return Array.from(props);
    }
    
    0 讨论(0)
  • 2020-11-22 13:48

    if you are trying to log non enumerable properties of a parent object ex. by default the methods defined inside a class in es6 are set on prototype but are set as non-enumerable.

    Object.getOwnPropertyNames(Object.getPrototypeOf(obj));
    
    0 讨论(0)
提交回复
热议问题