Vue app, Javascript, conditionally adding an Object to an array

假装没事ソ 提交于 2019-12-11 15:58:45

问题


I have a restaurant menu which is an array of objects each of which has the following properties:-

  • name
  • id - the id is autogenerated
  • 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

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? thanks in advance..


回答1:


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:

  • Pineapple Pizza (small) 1x
  • Pineapple Pizza (large) 1x

    You'd have to restructure your data if you'd want to

  • Pineapple Pizza 2x (small & large)

Your question doesn't really show what solution you want.



来源:https://stackoverflow.com/questions/52946848/vue-app-javascript-conditionally-adding-an-object-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!