Monday, August 19, 2019

How to push a object in array of objects in angular 7

This is question
this is code of me
CodeCart(){
   let itemList= this.orderService.getCart()
   let obj = {
     quantity : 1
   }
   itemList.push(obj);
   this.product = itemList
  console.log("get products",this.product);
}
This is my component.ts file and iam getting array of objects, i want to push an object "quantity" with value "0" in an array of obejcts.

i have this response.
this.orderService.getCart() = [{id: 48, title: "Mango Juices", price: "30", category: "juices"}]
Now, when I want to push me to get this result
0:{id: 48, title: "Mango Juices", price: "30", category: "juices"}
1:{quantity: 1}
This is answer
If I understand your problem, you need something like this
ngOnInit() {
    let itemList = [{ id: 48, title: "Mango Juices", price: "30", category: "juices" }]
    itemList.forEach((key) => {
      key["quantity"] = 0;
    })
    this.product = itemList
    console.log("get products", this.product); //[{id: 48, title: "Mango Juices", price: "30", category: "juices", quantity: 0}]
}

No comments:

Post a Comment