我想将一个对象id与数组中对象的所有id进行比较。
因此,我有一个按钮,可以将一道菜添加到订单数组中。当它不在数组中时,将其推送到数组中。但是当它确实存在时,用新的dish对象替换当前的。
const dish = {id:1, quantity: 4};
// This will be filled by an array push
const orders = [
{id: 1, dish: {id:1, quantity: 1}},
{id: 2, dish: {id:3, quantity: 5}},
{id: 3, dish: {id:5, quantity: 1}},
{id: 4, dish: {id:2, quantity: 3}},
{id: 5, dish: {id:8, quantity: 1}}
]
所以基本上我有一个
orderID
dishID
我所尝试的:
addToCart(dish){
const index = this.orders.findIndex((e) => e.id === dish.id);
if(index >= 0){
console.log('INDEX1', this.orders, index);
this.orders[index] = {id: this.orders[index].id, dish: this.orders[index].dish};
} else {
this.orderCounter = this.orderCounter + 1;
this.orders.push({id: this.orderCounter, dish: dish});
}
}
index
当我两次添加第三道菜时返回-1,如下所示:
dish = {id: 3, quantity: 2}
而orders数组如下所示:
const orders = [
{id: 0, dish: {id:1, quantity: 1}},
{id: 1, dish: {id:3, quantity: 2}},
{id: 2, dish: {id:3, quantity: 2}},
]
谁能帮帮我吗我很感激:)