Typescript - 没有动态添加属性的stringify类

时间:2017-07-25 16:49:33

标签: angular typescript

我已经启动了一组打字稿对象,但在代码中我需要动态地向这些对象添加一些属性。如果我需要通过加强对象来序列化对象 - 我该怎么做才能让它不包含动态添加的属性?由于我有大量的类和内部类,我正在寻找一个通用的方法,而不是逐个案例。

作为一个例子,我有一个以下列方式定义的类:

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

我正在寻找的是现在没有动态添加属性的对象的字符串表示,但方法是通用的,所以我不必描述我想要删除的内容。

所有需要的帮助; - )

3 个答案:

答案 0 :(得分:3)

您可以维护“已知密钥”的列表,并在序列化时使用它们:

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

答案 1 :(得分: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) });

答案 2 :(得分: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 }));
相关问题