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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With