简体   繁体   English

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:- 我有一个餐厅菜单,它是一个对象数组,每个对象都具有以下属性:-

  • name 名称
  • id - the id is autogenerated id-id是自动生成的
  • quantity 数量
  • options - which itself is an array that has two value pairs -size & price 选项-它本身是一个具有两个值对的数组-大小和价格

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 现在,我要允许用户在验证所选商品在购物车中不存在后将商品添加到购物车中,我面临的问题是,每个商品都有一个ID,但同时有两个或更多不同尺寸

Here is my code 这是我的代码

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

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? 上面的代码可以正常工作,除非当我尝试添加大小不同的相同披萨时,因为在这种情况下,ID会重复,因为每个项目都有一个ID,而不是每个披萨大小都有一个,所以任何人都可以想到一种解决方法? thanks in advance.. 提前致谢..

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: IE:

  • Pineapple Pizza (small) 1x 菠萝比萨(小)1x
  • Pineapple Pizza (large) 1x 菠萝比萨(大)1x

    You'd have to restructure your data if you'd want to 如果需要,您必须重组数据

  • Pineapple Pizza 2x (small & large) 菠萝披萨2x(大小)

Your question doesn't really show what solution you want. 您的问题并没有真正表明您想要什么解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM