2017-07-25 83 views
3

我有一組已啓動的typescript對象,但在代碼中我需要動態地將一些屬性添加到這些對象。如果我需要通過強化它來序列化對象 - 我該怎麼做才能使它不包含動態添加的屬性?由於我有大量的類和內部類,我正在尋找一種通用的方法,而不是一個一個的情況。Typescript - stringify類沒有動態添加屬性

因此,作爲一個例子,我有以下方式定義一個類:

export class Car { 

    public colour: string = ''; 
    public model: string = ''; 
    public diesel?: boolean = false; 

    constructor() {} 
} 

現在在代碼中,我設定了上述汽車作爲一個,我此刻的驅動器:

let car: Car = new Car(); 
car.model = 'modelA'; 
car.colour = 'black'; 

car['active'] = true; 

然後在某個地方的代碼我必須採取主動車,序列化對象,以便我可以將數據即發送到服務器:

JSON.stringify({'data': car}); 

我正在尋找的是現在沒有動態添加屬性的對象的字符串表示,但方法是通用的,所以我不必描述我想要刪除的內容。

所有虛位以待;-)

回答

1

可以維持的「已知鍵」列表,並使用這些序列化時:

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); 
    } 
} 

您可以使用裝飾器來創建此靜態列表。

或者:

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; 
} 
0

您可以創建一個車,它只會有正常的性能。然後遍歷它的各個屬性,並從另一輛車複製值:

let car: Car = new Car(); 
car.model = 'modelA'; 
car.colour = 'black'; 

car['active'] = true; 

let withoutDynamics = new Car(); 

for (let prop in withoutDynamics) { 
    // Check for hasOwnProperty if you like, depending on whether you 
    // properties from the prototype 
    withoutDynamics[prop] = car[prop]; 
} 

JSON.stringify({'data': withoutDynamics }); 

你可以考慮此因素伸到一個通用的功能與其他類使用(如果他們有一個構造函數沒有參數) :

function noDynamics<T>(type: { new(): T; }, withDynamics: T): T { 
    let withoutDynamics = new type(); 

    for (let prop in withoutDynamics) { 
     withoutDynamics[prop] = withDynamics[prop]; 
    } 

    return withoutDynamics; 
} 

JSON.stringify({'data': noDynamics(Car, car) }); 
0

可以保持原有的按鍵陣列在性能和使用自定義toJSON實現在你的類來控制,只有原來的按鍵得到系列化:

export class Car { 

    public colour: string = ''; 
    public model: string = ''; 
    public diesel?: boolean = false; 
    private _keys: string[] // Note that this is not initialized 

    constructor() { 
     this._keys = Object.keys(this); 
    } 

    toJSON() { 
     var obj: any = {}; 
     this._keys.forEach(key => { 
      obj[key] = this[key] 
     }); 
     return obj 
    } 
} 

let car: Car = new Car(); 
car.model = 'modelA'; 
car.colour = 'black'; 
car['active'] = true; 

console.log(JSON.stringify({ 'data': car }));