Reputation: 1323
I want to push a new key and corresponding value to an already existing object. My object is returned after subscribing to a WEB API endpoint. Within the object returned, I want to add a "QuantityOnHand" key and value. I have attempted the following, however, it is not as I want it.
branchProduct: BranchProduct;
getProductByName() {
const productName = this.addProductForm.get('product')?.value;
const quantity = this.addProductForm.get('quantity')?.value;
this.branchService.getProductByName(productName).subscribe((resp: any) => {
this.branchProduct = resp;
this.branchProduct.QuantityOnHand = quantity;
console.log(this.branchProduct);
})
}
The "branchProduct" interface class is as follows:
export interface BranchProduct {
BranchId: number;
ProductId: number;
ProductTypeName: string;
ProductName: string;
QuantityOnHand: number;
BaselineQuantity: number;
}
After assigning a value to the QuantityOnHand attribute, the object is logged as follows:
Would it be possible to set the QuantityOnHand as an actual additional attribute of the aforementioned object after the object is created? I have tried setting "branchProduct" as an array and pushing the value of the quantity through to it, however, I had no success doing so.
Any help is appreciated.
Upvotes: 2
Views: 5305
Reputation: 7
this.branchProduct is an array.
this.branchProduct[0].QuantityOnHand = quantity;
should work
Upvotes: 1
Reputation: 107
In the picture it's showing that branchProduct data is in 0 index of array. If branchProduct data always be one record on 0 index then you can fix it like.
getProductByName() {
const productName = this.addProductForm.get('product')?.value;
const quantity = this.addProductForm.get('quantity')?.value;
this.branchService.getProductByName(productName).subscribe((resp: any) => {
this.branchProduct = resp;
this.branchProduct[0].QuantityOnHand = quantity;
console.log(this.branchProduct);
})
}
Other wise you need to a implement a loop to modify the data.
const branchProductArray = []
branchProductObj.map((product, index) => {
let productObject = {... product };
productObject.QuantityOnHand = quantity;
branchProductArray.push(productObject)
})
console.log(branchProductArray). //will be desire result.
Upvotes: 1
Reputation: 2217
Use spread operator
this.branchProduct = {...resp, quantityonHand:quantity}
Upvotes: 0