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

后端 未结 9 1780
温柔的废话
温柔的废话 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));

提交回复
热议问题