I have the following class structure:
export abstract class PersonBase {
public toJSON(): string {
let obj = Object.assign(this);
let keys = Object.keys(this.constructor.prototype);
obj.toJSON = undefined;
return JSON.stringify(obj, keys);
}
}
export class Person extends PersonBase {
private readonly _firstName: string;
private readonly _lastName: string;
public constructor(firstName: string, lastName: string) {
this._firstName = firstName;
this._lastName = lastName;
}
public get first_name(): string {
return this._firstName;
}
public get last_name(): string {
return this._lastName;
}
}
export class DetailPerson extends Person {
private _address: string;
public constructor(firstName: string, lastName: string) {
super(firstName, lastName);
}
public get address(): string {
return this._address;
}
public set address(addy: string) {
this._address = addy;
}
}
I am trying to get toJSON
to output all the getters (excluding private properties) from the full object hierarchy.
So if I have a DetailPerson
instance and I call the toJSON
method, I want to see the following output:
{
"address": "Some Address",
"first_name": "My first name",
"last_name": "My last name"
}
I used one of the solutions from this Q&A but it doesn't solve my particular use case - I am not getting all the getters in the output.
What do I need to change here to get the result I am looking for?