我试图执行一个简单的forEach循环。
if (this.list.length == 0) {
this.list.push({ name, price, familly, quantity })
} else {
this.list_achat.forEach((element) => {
if (element.name === name && element.familly === familly) {
element.quantity += quantity
} else {
this.list.push({ name, price, familly, quantity })
}
this.prix_totale += element.quantity * element.price
})
}
当我首先添加一个产品以在list_achat.length == 0时添加list_achat,但是当我添加另一个产品时会发生什么
[
{"name":"prod1","price":"10","familly":"famille1","quantity":"4"},
{"name":"prod2","price":"10","familly":"famille1","quantity":"3"},
{"name":"prod2","price":"10","familly":"famille1","quantity":"2"},
{"name":"prod2","price":"10","familly":"famille1","quantity":1}
]
我想只保留
[
{"name":"prod1","price":"10","familly":"famille1","quantity":"4"},
{"name":"prod2","price":"10","familly":"famille1","quantity":"3"}
]
可能是什么问题?
答案 0 :(得分:0)
您每次调用forEach
回调时都会添加数组(适用于每个元素)。
你可能正在寻找Array.prototype.find
,它会返回数组中第一个回调一个真值的元素(如果没有找到undefined
):
const entry = this.list.find(e => e.name == name && e.familly == familly);
if (!entry) {
this.list.push({name,price,familly,quantity})
} else {
entry.quantity += quantity;
}