Skip to content

Instantly share code, notes, and snippets.

@zgover
Created December 16, 2020 21:10
Show Gist options
  • Save zgover/9d7b352a67e42343afb6f1743678cb25 to your computer and use it in GitHub Desktop.
Save zgover/9d7b352a67e42343afb6f1743678cb25 to your computer and use it in GitHub Desktop.
Class abstraction for automatic JSON generation
export default abstract class {
toJSON () {
const proto = Object.getPrototypeOf(this)
const jsonObj: any = Object.assign({}, this)
Object.entries(Object.getOwnPropertyDescriptors(proto))
// .filter(([_, descriptor]) => typeof descriptor.get === 'function')
.map(([key, descriptor]) => {
if (descriptor && key[0] !== '_') {
try {
jsonObj[`aaaaa${key}`] = (this as any)[key]
} catch (error) {
console.error(`Error calling getter ${key}`, error)
}
}
})
return jsonObj
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment