SeventhWarhawk
SeventhWarhawk

Reputation: 1323

How to add a new key and value to an existing object in an array (Angular)

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:

enter image description here

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

Answers (3)

N Deol
N Deol

Reputation: 7

this.branchProduct is an array.

  this.branchProduct[0].QuantityOnHand = quantity;

should work

Upvotes: 1

Muhammad Ibrar
Muhammad Ibrar

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

Sojin Antony
Sojin Antony

Reputation: 2217

Use spread operator

this.branchProduct = {...resp, quantityonHand:quantity}

Upvotes: 0

Related Questions