我正在开发一个食品车功能,将产品添加到购物车中。我的购物车是数组类型,产品是带有键值的对象。我面临的问题是,每当我尝试为相似的密钥添加具有不同值的新产品时,它也会覆盖旧产品的相同密钥的值。根据我的理解,数组只是指向我的产品对象的引用,但我想知道解决此问题的最佳方法是什么?我的代码结构如下:组件.tsthis.cartService.add(product); // <- This Product contains key modifier: ["abc","def"]购物车服务.tsadd(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: truekey: "-MMWt2wDMVaHqj45eKFg"modifiers: ["-MLxJCw0s0uDYSXYokz1"]name: "Single Modifier"price: 23qty: 1selectedModifiers: ["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__: Object1:category: "-M9JfAlqr_JiAiPTugc5"description: "zxfsfsafas afa fsaff fsf safsa sfaf safs afsafa fas asf safs af aasf asfa asf ."isAvail: truekey: "-MMWt2wDMVaHqj45eKFg"modifiers: ["-MLxJCw0s0uDYSXYokz1"]name: "Single Modifier"price: 23qty: 1selectedModifiers: ["Corn"] // <- This is correct but after adding this product, this selectedModifiers value also gets added to first product. See above.total: 23__proto__: Objectlength: 2__proto__: Array(0)任何想法,我怎样才能最佳地解决这个问题?
1 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
在修改产品对象之前克隆它
add(product) {
const clone = {...product}
clone.qty = 1;
clone.total = clone.price;
this.cart.push(clone);
}
添加回答
举报
0/150
提交
取消