首页 > 解决方案 > 如何以角度 6 将对象推入对象数组中

问题描述

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}

标签: angular

解决方案


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

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

推荐阅读