In the process of developing a food cart feature, I encountered an issue with my Array type cart and object products. Whenever I add a new product with a different value for a similar key, it ends up overwriting the existing values for all products in the cart. While I understand that an array is just a reference pointing to the product object, I need a solution to prevent this overwriting problem. Below is a snippet of how my code structure appears:
component.ts
this.cartService.add(product); // <- The Product contains key modifier: ["abc","def"]
cartService.ts
add(product) {
product.qty = 1;
product.total = product.price;
this.cart.push(product);
}
Each time I push a product with a different modifier key (e.g., modifier: ["dfg", "gght"]), it overrides the values of all modifier keys in the existing this.cart array objects. When I log the two products in this.cart array:
(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"] // <- Initially empty but gets populated after adding second product
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"]
total: 23
__proto__: Object
length: 2
__proto__: Array(0)
I am seeking advice on the optimal way to resolve this issue. Any ideas?