I want to convert an instance class to a simple object without losing methods and / or inherited properties. For example:
class Human {
height: number;
weight: number;
constructor() {
this.height = 180;
this.weight = 180;
}
getWeight() { return this.weight; }
toJSON() {
return {};
}
}
class Person extends Human {
public name: string;
constructor() {
super();
this.name = 'Doe';
}
public getName() {
return this.name;
}
}
class PersonWorker extends Person {
constructor() {
super();
}
public report() {
console.log('I am Working');
}
public test() {
console.log('something');
}
}
let p = new PersonWorker;
let jsoned = p.toJSON();
jsoned should look like this:
{
height: 180,
weight: 180,
getWeight: function() {return this.weight},
name: 'Doe'
getName(): function() {return this.name},
report: function() { console.log('I am Working'); },
test: function() { console.log('something'); }
}
Can this be done, and if so, how?
If you're interested, I need this because I use a framework that, unfortunately, only accepts a json object as input, while I try to use typescriptclass inheritance as well.
In addition, I am doing the above conversion, so that performance is not a problem to consider.
UPDATE
, , , es6. es5 ( Object.keys(instance)).
:
toJSON(proto?: any) {
let jsoned: any = {};
let toConvert = <any>proto || this;
Object.getOwnPropertyNames(toConvert).forEach((prop) => {
const val = toConvert[prop];
if (prop === 'toJSON' || prop === 'constructor') {
return;
}
if (typeof val === 'function') {
jsoned[prop] = val.bind(this);
return;
}
jsoned[prop] = val;
const proto = Object.getPrototypeOf(toConvert);
if (proto !== null) {
Object.keys(this.toJSON(proto)).forEach(key => {
if (!!jsoned[key] || key === 'constructor' || key === 'toJSON') return;
if (typeof proto[key] === 'function') {
jsoned[key] = proto[key].bind(this);
return;
}
jsoned[key] = proto[key];
});
}
});
return jsoned;
}
. , PersonWorker.
?