我有以下类结构:
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;
}
}
我想得到toJSON
输出完整对象层次结构中的所有 getter(不包括私有属性)。
所以如果我有一个DetailPerson
实例,我称之为toJSON
方法,我想看到以下输出:
{
"address": "Some Address",
"first_name": "My first name",
"last_name": "My last name"
}
我使用了以下解决方案之一本次问答 https://stackoverflow.com/questions/40080473/using-json-stringify-in-conjunction-with-typescript-getter-setter但它并没有解决我的特定用例 - 我没有在输出中得到所有的吸气剂。
我需要在这里更改什么才能获得我想要的结果?
您提供的链接使用Object.keys
这遗漏了原型上的属性。
你可以使用for...in
代替Object.keys
:
public toJSON(): string {
let obj: any = {};
for (let key in this) {
if (key[0] !== '_') {
obj[key] = this[key];
}
}
return JSON.stringify(obj);
}
Edit:这是我尝试仅递归地返回吸气剂,而不假设非吸气剂以下划线开头。我确信我错过了一些问题(循环引用、某些类型的问题),但这是一个好的开始:
abstract class PersonBase {
public toJSON(): string {
return JSON.stringify(this._onlyGetters(this));
}
private _onlyGetters(obj: any): any {
// Gotchas: types for which typeof returns "object"
if (obj === null || obj instanceof Array || obj instanceof Date) {
return obj;
}
let onlyGetters: any = {};
// Iterate over each property for this object and its prototypes. We'll get each
// property only once regardless of how many times it exists on parent prototypes.
for (let key in obj) {
let proto = obj;
// Check getOwnPropertyDescriptor to see if the property is a getter. It will only
// return the descriptor for properties on this object (not prototypes), so we have
// to walk the prototype chain.
while (proto) {
let descriptor = Object.getOwnPropertyDescriptor(proto, key);
if (descriptor && descriptor.get) {
// Access the getter on the original object (not proto), because while the getter
// may be defined on proto, we want the property it gets to be the one from the
// lowest level
let val = obj[key];
if (typeof val === 'object') {
onlyGetters[key] = this._onlyGetters(val);
} else {
onlyGetters[key] = val;
}
proto = null;
} else {
proto = Object.getPrototypeOf(proto);
}
}
}
return onlyGetters;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)