angular - Typescript - stringify class without dynamically added properties -
i have set of typescript objects has been initiated, in code need dynamically add properties object. if need serialize object stingifying - how can won't include dynamically added properties? have loads of classes , inner classes looking generic approach rather 1 one case.
so example have class defined in following way:
export class car { public colour: string = ''; public model: string = ''; public diesel?: boolean = false; constructor () {} }
now in code setting above car 1 drive @ moment:
let car: car = new car(); car.model = 'modela'; car.colour = 'black'; car['active'] = true;
and somewhere in code have take active car , serialize object can i.e. send data server:
json.stringify({'data': car});
what looking string representation of object without dynamically added properties, approach generic don't have describe want remove.
all wanted ;-)
you can maintain list of "known keys" , use them when serializing:
class car { private static keys = ["colour", "model", "diesel"]; public colour: string = ''; public model: string = ''; public diesel?: boolean = false; constructor() { } tojsonstring(): string { const data = {}; car.keys.foreach(key => data[key] = this[key]); return json.stringify(data); } }
you can use decorators create static list.
or:
class car { public colour: string = ''; public model: string = ''; public diesel?: boolean = false; constructor() { this.tojsonstring = function (keys) { const data = {}; keys.foreach(key => data[key] = this[key]); return json.stringify(data); }.bind(this, object.keys(this)); } tojsonstring: () => string; }
Comments
Post a Comment