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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -