如何使用 array.push() 函数复制数组而不重复键值?

我正在开发一个食品车功能,将产品添加到购物车中。我的购物车是数组类型,产品是带有键值的对象。我面临的问题是,每当我尝试为相似的密钥添加具有不同值的新产品时,它也会覆盖旧产品的相同密钥的值。根据我的理解,数组只是指向我的产品对象的引用,但我想知道解决此问题的最佳方法是什么?我的代码结构如下:


组件.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)

任何想法,我怎样才能最佳地解决这个问题?


富国沪深
浏览 139回答 1
1回答

潇湘沐

在修改产品对象之前克隆它&nbsp; &nbsp;add(product) {&nbsp; &nbsp; &nbsp; &nbsp;const clone = {...product}&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;clone.qty = 1;&nbsp; &nbsp; &nbsp; &nbsp;clone.total = clone.price;&nbsp; &nbsp; &nbsp; &nbsp;this.cart.push(clone);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript