Skip to content
Advertisement

How to copy the array with array.push() function without duplicate key value?

I am developing a food cart function where I am adding products to the cart. My cart is an Array type and the product is an object with key-values. The problem I am facing is, whenever I am trying to add a new product with a different value for a similar key, it overwrites the value of the same key for the old product as well. As per my understanding, an array is just a reference pointing to my product object but I want to know, what is the best method to resolve this issue? Here is how my code structure looks like:

component.ts

this.cartService.add(product); // <- This Product contains key modifier: ["abc","def"]

cartService.ts

add(product) {
   product.qty = 1;
   product.total = product.price;
   this.cart.push(product);
}

So every time I push the product to the cart with a different modifier key (for example -> modifier: [“dfg”, “gght”]), it overwrites the existing this.cart array objects with a new value for all modifier keys.

Here is how the two products inside my this.cart array gets logged:

(2) [{…}, {…}]
0:
category: "-M9JfAlqr_JiAiPTugc5"
description: "zxfsfsafas afa fsaff fsf safsa sfaf safs afsafa fas asf safs af aasf asfa asf ."
isAvail: true
key: "-MMWt2wDMVaHqj45eKFg"
modifiers: ["-MLxJCw0s0uDYSXYokz1"]
name: "Single Modifier"
price: 23
qty: 1
selectedModifiers: ["Corn"]  // <- This is initially empty when I added this product but after adding second product this also took the value of second.
total: 23
__proto__: Object

1:
category: "-M9JfAlqr_JiAiPTugc5"
description: "zxfsfsafas afa fsaff fsf safsa sfaf safs afsafa fas asf safs af aasf asfa asf ."
isAvail: true
key: "-MMWt2wDMVaHqj45eKFg"
modifiers: ["-MLxJCw0s0uDYSXYokz1"]
name: "Single Modifier"
price: 23
qty: 1
selectedModifiers: ["Corn"] // <- This is correct but after adding this product, this selectedModifiers value also gets added to first product. See above.
total: 23
__proto__: Object
length: 2
__proto__: Array(0)

Any idea, how can I resolve this issue optimally?

Advertisement

Answer

Clone the product object before modifying it

   add(product) {
       const clone = {...product} 
       clone.qty = 1;
       clone.total = clone.price;
       this.cart.push(clone);
    }
Advertisement