如何使用 array.push() 函数复制没有重复键值的数组?

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

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

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);
}

因此,每次我使用不同的修饰键(例如 -> 修饰符:["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)

知道吗,我怎样才能最佳地解决这个问题?

在修改之前克隆产品对象

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