15

Let's say I have this class (which I using like an enum):

class Color {
    static get Red() {
        return 0;
    }
    static get Black() {
        return 1;
    }
}

Is there anything similar to Object.keys to get ['Red', 'Black']?

I'm using Node.js v6.5.0 which means some features might be missing.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
Almis
  • 3,684
  • 2
  • 28
  • 58
  • 1
    @Gothdo: `Object.keys` doesn't filter for getters either, so I assumed the OP would know how to check whether it's a getter, data property, method or something else. – Bergi Sep 03 '16 at 20:18
  • @Bergi I not familiar with JS getters, I gave `Object.keys` as an example because it's the closest thing that came to my mind. – Almis Sep 03 '16 at 20:28

1 Answers1

24

Use Object.getOwnPropertyDescriptors() and filter the results to contain only properties which have getters:

class Color {
    static get Red() {
        return 0;
    }
    static get Black() {
        return 1;
    }
}

const getters = Object.entries(Object.getOwnPropertyDescriptors(Color))
  .filter(([key, descriptor]) => typeof descriptor.get === 'function')
  .map(([key]) => key)

console.log(getters)

You can also try this approach—it should work in Node.js 6.5.0.

class Color {
    static get Red() {
        return 0;
    }
    static get Black() {
        return 1;
    }
}

const getters = Object.getOwnPropertyNames(Color)
  .map(key => [key, Object.getOwnPropertyDescriptor(Color, key)])
  .filter(([key, descriptor]) => typeof descriptor.get === 'function')
  .map(([key]) => key)

console.log(getters)
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • 3
    Just a heads up that this is also a valid method for retrieving *non*-static getters, one just looks up in `Color.prototype` instead of `Color`. – Ilya Semenov Oct 15 '20 at 16:25
  • `const getters = Object.getOwnPropertyNames(Object.getPrototypeOf(this)).filter(prop => prop.startsWith('get'));` – daniel p Nov 10 '22 at 14:57