Vue应用程序,JavaScript,有条件地将对象添加到数组 [英] Vue app, Javascript, conditionally adding an Object to an array
问题描述
我有一个餐厅菜单,该菜单是一个对象数组,每个对象都具有以下属性:-
I have a restaurant menu which is an array of objects each of which has the following properties:-
- 名称
- id-ID是自动生成的
- 数量
- options-它本身是一个具有两个值对的数组-size&价格
现在,我要允许用户在验证所选商品不在购物车中之后,将商品添加到购物车中,我面临的问题是,每个商品都有一个ID,但同时时间有两个或更多个不同的大小
Now, I want to allow the user to add items to the shopping cart after validating that the selected Item doesn't already exist in the cart, the problem I am facing is, each Item has an Id, but at the same time has two or more different sizes
这是我的代码
export default {
data(){
return {
cart: []
}
}
//...
methods: {
addItem(pizza, options){
let selectedPizza= {
id: pizza.id,
name: pizza.name,
size: options.size,
price: options.price
quantity: 1
}
if(this.cart.length > 0) {
this.cart.forEach(item => {
if(item.name === selectedPizza.name && item.size === selectedPizza.size && item.id === selectedPizza.id) {
return item.quantity++
} else {
this.cart.push(selectedPizza)
}
})
} else {
this.cart.push(selectedPizza)
}
}
}
}
上面的代码可以正常工作,除非当我尝试添加大小不同的同一个披萨时,因为在这种情况下,ID会重复出现,因为每个项目都有一个ID,并不是每个披萨大小都有一个,任何人都可以想到解决方法? 预先感谢..
the code above works fine except when I try to add the same pizza with a different size, because the id, in this case, is repeated as each item has the an Id, not every pizza size has one, anyone can think of a workaround? thanks in advance..
推荐答案
这似乎更多是数据结构问题,而不是语法或编码问题.在您的情况下,我将添加一个重复的比萨饼,每个比萨饼一个.这样,您仍然可以增加金额. IE浏览器:
This seems more of a data structure issue rather than a syntax or coding issue. In your case I'd add a duplicate pizza, one for each size. That way you can still increment the amount. IE:
-
菠萝比萨(小)1x
Pineapple Pizza (small) 1x
菠萝比萨(大)1x
如果需要,您必须重组数据
You'd have to restructure your data if you'd want to
菠萝披萨2x(小和大)
Pineapple Pizza 2x (small & large)
您的问题并没有真正显示您想要的解决方案.
Your question doesn't really show what solution you want.
这篇关于Vue应用程序,JavaScript,有条件地将对象添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!