combine and refresh identical items within an array

Currently, I am in the process of creating a prototype for an item-list and a shopping-cart. Both components function as standalone entities but are connected through a vuex-store. The item-list contains various elements that can be added to the shopping-cart with different quantities. When an item is added, it becomes an object with specific information (such as id, name, quantity) stored in an array named "products". This object is then displayed within the shopping cart. The issue arises when adding the same element to the shopping-cart with different quantities. While it is correctly added as a new item, I would like the system to update the quantity and price of the existing item rather than duplicating it. Therefore, there needs to be a check implemented to identify if the same element (based on its id) already exists in the shopping-cart and consolidate them. I hope my explanation is clear :D

The function responsible for adding elements to the array looks like this:

addToBasket(key) {
          if (this.products[key].qty >= 1) {
            this.$store.commit('addProduct', {
              id: this.products[key].product_id,
              title: this.products[key].title,
              price: {
                value: this.products[key].price.value,
                currency: this.products[key].price.currency,
              },
              qty: this.products[key].qty
            });
          }
        }

The corresponding mutation within the store is as follows:

addProduct(state, payload) {
    state.products.push(payload);
}

Answer №1

It's important to store data in key: value pairs, where the key represents the item name and the value represents the quantity of that item.

Before adding a new entry, always check the variable holding the stored data to see if the key, in this case 'state', already exists. If it does, update only the value ('payload'). Otherwise, add both the state and payload.

if ("key" is present in myObj)
{
    //Code to update the payload
}
else
{
    //Code to insert the key and value pair
}

For more information, click here

Alternatively, you can use the following method:

function keyExists(key, search) {
        if (!search || (search.constructor !== Array && search.constructor !== Object)) {
            return false;
        }
        for (var i = 0; i < search.length; i++) {
            if (search[i] === key) {
                return true;
            }
        }
        return key in search;
    }

// Usage:
// Searching for keys in Arrays
console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true
console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false

// Searching for keys in Objects
console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true
console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false

An optimized way to perform the check:

yourObjName.hasOwnProperty(key) : 
{
//Code to add the payload alone 
}
? 
{
//Code to push both state and payload;
}

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

Creating a jQuery Mobile Multi-Select feature with dynamically loaded data

I'm facing an issue with integrating jQuery Mobile and AngularJS. I need a multi-select option for users to choose categories, which have parent-child relationships. The data structure is fetched asynchronously from a database. The problem is that t ...

Is it possible for me to set a timer on the 'keyup' event in order to decrease the frequency of updates?

The code I currently have is functional: $wmdInput.on('keyup', function () { var rawContent = $wmdInput.val(); scope.$apply(function () { ngModel.$setViewValue(rawContent); }); }); Unfortunately, it appears to slow down my t ...

How to add an image in raw HTML using Vue.js

When trying to style text from an object property in an array, I decided to use the v-html attribute. However, my attempts to insert an image using various syntaxes have been unsuccessful. <img :src="@/assets/image.png" alt="image descrip ...

Issue with hidden sourcemap not loading in Chrome or Firefox during Vite build

Transitioning my react application from create-react-app to Vite has resulted in some unexpected behavior with source maps. To learn more about Vite's documentation on source maps, click here. Initially, I was thinking of using sourcemap: true, but th ...

Create a script that ensures my website can be set as the homepage on any internet browser

I am currently in search of a way to prompt users on my website to set it as their homepage. Upon clicking "Yes," I would like to execute a script that will automatically make my website the user's browser homepage. I have come across a Similar Thread ...

What is the best way to create shaded areas upon clicking them?

How can I implement shading on areas when they are clicked? Contractor Form (Package One) <area id="39" name ="39" alt="" title="39" href="#" shape="poly" coords="12,204,12,120,138,117,144,72,248,72,252,124,526,125,632,81,668,157,698,149,722,2 ...

What is the best approach for managing Promise rejections in Jest test scenarios?

Currently, I am engaged in a node JS project where my task is to write test cases. Below is the code snippet that I am working on - jest.mock('../../utils/db2.js') const request = require('supertest') const executeDb2Query = require(&ap ...

What is the reason for the Pinia Persistedstate Plugin breaking when the statement "useUserStore(store)" is called in a Quasar boot file?

Currently, I am attempting to integrate the Pinia Persisted State Plugin with Pinia in my Quasar application (Vue 3 / TypeScript). Initially, everything functions correctly right out of the box. However, the persisted state ceases to operate when incorpo ...

Leveraging ForEach to merge two arrays and generate a fresh entity

I am in search of my final result which should be as follows: result = [{x: '12/12', y: 90 }, {x: '12/11', y: 0}, {x: '12/10', y: 92}, {x: '12/9', y: 0}, ... ] Currently, I have two arrays to work with. The first a ...

Using Ajax on a WordPress webpage

I am currently experimenting with this piece of Ajax jQuery code within a WordPress page: 1. <script> 2. $(document).ready(function(){ 3. $("button").click(function(){ 4. $.ajax({ 5. method: 'GET', 6. ...

Carousel Alert: Ensure that every child within the list is assigned a distinct "key" property

I'm experiencing an issue that is proving to be more challenging than usual, as it appears to be related to a specific library. I understand that using a key from a file is not ideal, but the plan is for it to come from a database in the future. Libr ...

Creating an Add-in using the Excel JavaScript API based on an already existing spreadsheet

Is there a way to create an Add-in using Excel JavaScript API from an existing spreadsheet? When running npm start, it generates a blank workbook. I believe changes need to be made in the Manifest.xml file, as npm start triggers office-addin-debugging star ...

What could be the reason for the error message "cy.intercept is not recognized as a function

When attempting to intercept a POST request, I encountered the following error: view image description here This is my sample code: view image description here I came across a similar issue on Stack Overflow: cy.intercept is not a function Cypress tes ...

Parcel React component library throws an error stating that "require is not defined

Error message: Uncaught ReferenceError: require is not defined at index.js?5WdmUIncGTkIrWhONvlEDQ:1:1 (anonymous) @ index.js?5WdmUIncGTkIrWhONvlEDQ:1 First lines of index.js: require("./index.css"); var $cI6W1$lodash = require("lodash&q ...

Tips for switching images in a grid using jQuery

I have implemented an image grid using flexbox on a website I am developing. The grid consists of 8 boxes, and my goal is to randomly select one box every 2 seconds and assign it one of 12 random images. My strategy involves creating an array containing UR ...

How can I hide the drawer in Vuetify?

After adding navigation to the drawer, I encountered an issue where the drawer remains open when clicking on a link that goes to the same page. This can be confusing for visitors as it doesn't indicate that they are already on the current page. I att ...

Securing API routes in Laravel

I have a Laravel application integrated with VUEJS for the front-end. I am retrieving data through API Routes. As an example, the route to fetch posts data is http://localhost/api/posts What would be the most effective method to secure my routes? After r ...

Troubleshooting Issue: ASP.NET UpdatePanel Not Responding to jQuery

I am having difficulties invoking jQuery functions within an "asp:UpdatePanel". Despite the code provided below, my attempts to add a class to the div element ".popup-body" are unsuccessful. Interestingly, the "alert();" function works without any issues. ...

Add a fresh column in the table that includes modified values from an existing column, affected by a multiplication factor provided through a text input

I'm currently working on a Laravel website where I have a pricing table sourced from a database. The Retail Price column in this table serves as the base for calculating and populating a Discount Price column using a multiplier specified in a text inp ...

ScrollReveal.js won't function as intended

https://i.stack.imgur.com/SOQEk.png Looking to utilize the popular ScrollReveal.js created by Julian Lloyd (ScrollReveal) Despite following instructions from various sources, the script is not producing the intended effect. Steps taken to make it work: ...