我正在开发一个食品车功能,将产品添加到购物车中。我的购物车是数组类型,产品是带有键值的对象。我面临的问题是,每当我尝试为相似的密钥添加具有不同值的新产品时,它也会覆盖旧产品的相同密钥的值。根据我的理解,数组只是指向我的产品对象的引用,但我想知道解决此问题的最佳方法是什么?我的代码结构如下:
组件.ts
this.cartService.add(product); // <- This Product contains key modifier: ["abc","def"]
购物车服务.ts
add(product) {
product.qty = 1;
product.total = product.price;
this.cart.push(product);
}
因此,每次我使用不同的修饰键(例如 -> 修饰符:["dfg", "gght"])将产品推入购物车时,它都会使用所有修饰键的新值覆盖现有的 this.cart 数组对象。
以下是我的 this.cart 数组中的两个产品的记录方式:
(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)
任何想法,我怎样才能最佳地解决这个问题?
潇湘沐
相关分类