hussain
hussain

Reputation: 7123

How to add property to object using typescript?

I have objects that i parsed to build final object , so i tried to add tempObject1 and tempObject2 to OrderRequest but it is not adding to object. So i have mentioned how i want output after processing.

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

output

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

Upvotes: 0

Views: 255

Answers (1)

Ajanth
Ajanth

Reputation: 2515

You're re-assigning this.containingJSON['OrderRequest'] in your code, instead of creating new properties. Based on how you want, following is the updated code

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

Upvotes: 2

Related Questions