如何使用typescript将属性添加到对象?

时间:2018-06-05 19:03:19

标签: javascript typescript

我有解析后构建最终对象的对象,所以我尝试将tempObject1tempObject2添加到OrderRequest,但它没有添加到对象。所以我在处理后提到了我想要的输出。

index.ts

export class OrderRequest {
private containingJSON = {"OrderRequest": {}};;
    public rxOrderRequest(_request: any): OrderRequest {

                const tempObject1: object = Object.assign({}, JSON.parse(strInfo));

                const tempObject2: object = Object.assign({}, JSON.parse(strNonType),
                    JSON.parse(strType)
                );
                this.containingJSON['OrderRequest'] = tempObject1;
                this.containingJSON['OrderRequest']= tempObject2


                return this;
            }
}

输出

"OrderRequest": {
        User:{},
        Order: {nonCrittical:Object,critical:object}
}

1 个答案:

答案 0 :(得分:2)

您在代码中重新分配this.containingJSON [' OrderRequest'],而不是创建新属性。 根据您的需要,以下是更新的代码

export class OrderRequest {
private containingJSON = {"OrderRequest": {}};;
    public rxOrderRequest(_request: any): OrderRequest {

                const tempObject1: object = Object.assign({}, JSON.parse(strInfo));

                const tempObject2: object = Object.assign({}, JSON.parse(strNonType),
                    JSON.parse(strType)
                );
                this.containingJSON['OrderRequest']['tempObject1'] = tempObject1;// assign tempObject1 to a new property "tempObject1"
                this.containingJSON['OrderRequest']['tempObject2'] = tempObject2;


                return this;
            }
}