如何在角度6的对象数组中推送对象

时间:2018-07-24 07:49:22

标签: angular

cart(){

   let itemList= this.orderService.getCart()
   let obj = {
     quantity : 1
   }
   itemList.push(obj);
   this.product = itemList
  console.log("get products",this.product);
}

这是我的component.ts文件,并且我正在获取对象数组,我想在对象数组中推送值为“ 0”的对象“数量”。 我有这个回应

this.orderService.getCart() = [{id: 48, title: "Mango Juices", price: "30", category: "juices"}]

现在当我要推动时,我得到了这个结果。...

0:{id: 48, title: "Mango Juices", price: "30", category: "juices"}

1:{quantity: 1}

2 个答案:

答案 0 :(得分:3)

如果我理解您的问题,您需要类似的东西

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

答案 1 :(得分:0)

[{id: 48, title: "Mango Juices", price: "30", category: "juices"}]是一个对象数组。

要将属性推入对象,只需简单地获取对象并添加新属性:

let itemList = [{ id: 48, title: "Mango Juices", price: "30", category: "juices" }] 
itemList[0]["quantity"] = 1;

如果要为数组中的所有对象添加新属性,则@Sanoj_V的答案就是如此。

柱塞工作:https://stackblitz.com/edit/angular-qne3cl