Created
December 16, 2020 21:10
-
-
Save zgover/9d7b352a67e42343afb6f1743678cb25 to your computer and use it in GitHub Desktop.
Class abstraction for automatic JSON generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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