2
cart(){

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

and now when i am going to push i get this result....

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

1:{quantity: 1}
3
  • It seems you are mixing objects and arrays. There is ONE Object in the array. And it seems you don´t want to push a second value onto this array, but to give the one object in the array an additional attribute "quantitiy". Am i right? Commented Jul 24, 2018 at 7:59
  • yes i want to add "quantity" attribute in id:48 object Commented Jul 24, 2018 at 8:07
  • The push() method adds new items to the end of an array. What you want is to add a new property to the JavaScript object. Refer to the answer by @Sanoj_V Commented Jul 24, 2018 at 8:22

2 Answers 2

5

If i understood your question you need something like that

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}]
}
Sign up to request clarification or add additional context in comments.

Comments

0

[{id: 48, title: "Mango Juices", price: "30", category: "juices"}] is an array of objects.

To push a property to your object, you just simply take your object and add your new property:

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

If you want to add the new property for all object in the array, the answer of @Sanoj_V is for that.

Plunker works:https://stackblitz.com/edit/angular-qne3cl

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.