Using Vue app and Javascript to dynamically add an object to an array based on a certain condition

I'm currently working on a restaurant menu project where each item is an object with properties such as name, id (which is autogenerated), quantity, and options. Each option includes size and price values nested within an array.

My goal is to allow users to add items to their shopping cart while ensuring that duplicate items are not added. However, I'm facing a challenge because each item has a unique id, but can come in multiple sizes.

Below is a snippet of 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)
      }
    } 
  }
}

While the code above functions well for adding pizzas of the same size, it encounters issues when attempting to add the same pizza in different sizes due to the repeated id. Does anyone have a workaround or solution for this scenario? Your help is much appreciated!

Answer №1

It appears that the issue lies within the data structure rather than a problem with syntax or coding. One possible solution could be to add a duplicate pizza for each size in order to properly increment the amount. For example:

  • Pineapple Pizza (small) 1x

  • Pineapple Pizza (large) 1x

    If you would like a different solution, you may need to reevaluate how your data is organized.

  • Pineapple Pizza 2x (small & large)

It's important to clarify what specific outcome you are seeking with this question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for executing a Python function from JavaScript, receiving input from an HTML text box

Currently, I am facing an issue with passing input from an HTML text box to a JavaScript variable. Once the input is stored in the JavaScript variable, it needs to be passed to a Python function for execution. Can someone provide assistance with this pro ...

Getting the time difference relative to the current time using date-fns from a MySQL datetime - a step

I am trying to implement a relative time feature like ... ago in my react blog posts without relying on moment.js. The date of the post is stored in mysql using the datatime data type, for example 2023-02-01 21:25:33 This is what I have attempted in the c ...

The web page's content remains hidden until it is scrolled into view, despite the fact that the page has finished loading

I'm a beginner with Angular and currently working on creating a website. On the following page , when viewed on mobile, I am experiencing an issue where the content doesn't load until it's brought into view by scrolling down the page. I am u ...

Exploring the dynamic loading of JavaScript functions with Ajax in Dojo while passing arguments

Currently, I am working on implementing a require/load function that handles the retrieval and execution of remote JavaScript code. The function is functioning well, but I have been using a workaround to pass arguments by setting global variables. However, ...

Achieving the perfect sorting result in an array using Javascript

I am attempting to arrange the objects inside an array below in ascending order by their values and achieve the desired output as shown: var arr = [{"DOA Qty":"0.000665921017598927382910198160","LOS%":"0","FID Valid EC By Part":"0.004186044328301671376196 ...

the scroll feature is malfunctioning within the AngularJS div container

In the process of developing a platform, I have integrated Angular.js as the framework. However, when adding my custom HTML code to the homepage, it seems to be causing issues with the existing codebase. Can someone please review the code and point out any ...

Why does the type of obj.getClass() in Java return Class<?> instead of Class<? extends T>?

Question: <T> void foo(T obj) Why is the type of obj.getClass() Class<?> instead of Class<? extends T> in a generic function like this? Even though the code below works fine: String foo = ""; Class<? extends String> fooClass = f ...

Navigating through the elements of the DOM

Here is a function that deletes people from a list when you click on a certain part of the form: function ParticipantsDeleteClick(model, url) { for (i in model.Participants) { $("#delete" + i).click(function () { $.ajax({ url: url, ...

Retrieve the value of the key in my AngularJS JSON object

Describing my object object1 ={ name: xxx, Id: 212 } I want to transform it into: { 212:xxx } Is there anyone who can guide me on how to achieve this? for(var key in object1) { if(object1.hasOwnProperty(key)) { console.log( eac ...

Vuetify 2 to 3 struggles with aligning children in v-text-field components, particularly the prepend-inner and append elements that appear to be overlooked

Struggling with the migration of legacy code from Vuetify 2 to 3. Specifically, encountering issues with v-text-field child components. Despite attempting various solutions found on StackOverflow and Google, none have successfully resolved the problem - on ...

What could be the reason for the undefined return from .forEach method?

While I have come across several questions on this particular topic , none of them have been able to provide me with a solution. Let's take a look at the data I am working with: const testsMap = { 0: ["just", "test"], 1: ["b ...

Searching for the location of a specific item within an array using

Trying to grasp the fundamental components of Javascript has led me to stumble upon a specific line of code: if (varX.indexOf(String(varY),0) < 0) In this scenario, varX represents an array of Strings and varY is one of the strings contained within th ...

Observe the present time in a specific nation

Is there an authorized method to obtain and showcase the current accurate GMT time instead of relying on the easily manipulable local time on a computer? I am looking for a reliable way to acquire the current time in hours/minutes, so I can make calculati ...

Styling div elements to match the dimensions of table rows in CSS

When it comes to CSS, I wouldn't call myself an expert; My question is: is there a way for a div tag to inherit dimensions from specific table rows based on their class or id? For instance: Imagine we have a table with multiple rows, but we don&apos ...

Utilizing Angular: Integrating the Http response output into a map

I have a situation where I am making multiple HTTP calls simultaneously from my Angular application. The goal is to store the responses of these calls in a Map. data: Map<number, any> = new map<number,any>(); --------------------------------- ...

What is the origin of the `billable` variable used in the Laravel Spark `update-payment-method-stripe` component?

When using Laravel Spark, a vue component is included with the following inline template: <spark-update-payment-method-stripe :user="user" :team="team" :billable-type="billableType" inline-template> /* ... */ <div class="pull-righ ...

Tips on resolving the Hydration error in localStorage while using Next.js

Having issues persisting context using localStorage in a Next.js project, resulting in hydration error upon page refresh. Any ideas on how to resolve this issue? type AppState = { name: string; salary: number; info: { email: string; departme ...

JS Tips for using the .push() function with Multidimensional Arrays in JavaScript

After coming across this code example online, I decided to give it a try. The code snippet involved using the JavaScript array push method to add new elements to an inner sub-array, which was exactly what I needed to achieve! The code successfully demons ...

When utilizing an object within another object for a select option in Vue.js, the value may not update as expected

I'm currently working with an array of posts that includes a user for each post. I have a select field where I can change the user associated with a post. However, only the user's id updates on the page and not their username. Is there a way to e ...

Utilizing Vue JS to Retrieve External POST Data for Enhanced Application Functionality

In the process of developing a Vue JS application, I have encountered a scenario where I need to interact with a third-party financial transaction service. This service provider sends encrypted data within the body of a POST method using FormData and then ...