What is the best way to verify the values in a specific array and adjust them by increasing or decreasing?

I am managing a shopping basket stored as an array in local storage. How can I efficiently check for a specific value and then increment or decrement it?

Below is the code snippet:

I need to verify if a ProductID is present, make necessary adjustments, and update the local storage accordingly.

var Basket = {
    ProductID: product,
    Quantity: quantity
};

//Step 2 - create an array 
//  
var BasketContents = [];
if (localStorage.getItem('BasketContents') !== null) {
    BasketContents.push(JSON.parse(localStorage.getItem('BasketContents')));
}

//Step 3 - create an array of objects
BasketContents.push(Basket);
localStorage.setItem('BasketContents', JSON.stringify(BasketContents));

Answer №1

To work around this issue, one solution is to store an array of objects where each object represents a basket with the product ID as the key. This approach provides more clarity and simplicity compared to saving all objects in a single container.

  1. Start by fetching all the required baskets and organizing them into an array:
const basket = [{productId: 2, quantity:5}, {productId: 6, quantity: 4}, {productId: 4, quantity: 18}, {productId: 3, quantity: 5}]
  1. Save the basket array in localStorage: localStorage.setItem('basketContainer', JSON.stringify(basket))

  2. When it's time to update the list/array, retrieve the basketContainer from localStorage and iterate through it.

const update = JSON.parse(localStorage.getItem('basketContainer'))
update.forEach(item => {
    if (item.productId == 4) {
        item.quantity += 1
    }
})

You can log the 'update' variable at this stage to see the changes reflected.

Similarly, create a function for incrementing or decrementing quantities:

const incrementDecrement = (list, action) => {
    update.forEach(item => {
        if (item.productId == 4) {
            // Use action parameter to determine increment (+) or decrement (-)
            item.quantity `${action}`= 1
        }
    })
}

After making updates, save the data back to your localStorage using the same name:

localStorage.setItem('basketContainer', JSON.stringify(update))

Best of luck implementing these changes!

It's also recommended to consider alternatives to local storage. For further insights, check out this article: stop_using_localStorage

Answer №2

This seems like a straightforward approach

If the data is stored in the format

{ ProductID: 241, Quantity: quantity }

// Check if BasketContents exists
if(localStorage.BasketContents){
    // If it does
    let BasketContents = JSON.parse( localStorage.BasketContents );
    // Increase ProductID by 5
    BasketContents.ProductID += 5;
    // Update local storage
    localStorage.BasketContents = JSON.stringify(BasketContents);
}

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

Stop user from navigating to specific route using React-router

I am currently utilizing react-router with history useQueries(createHashHistory)(), and I have a requirement to restrict navigation to certain routes based on the route's configuration. The route configuration looks like this: <Route path="/" name ...

When the update button is clicked, the textfield is hidden; it reappears upon refreshing the page

Our marketplace multi-vendor site on Magento allows sellers to list their products for sale. The frontend displays the price using the following code: Phtml <input onFocus="showPriceCancel('<?php echo $products->getId(); ?>');" clas ...

Is it possible to manipulate the response from a MySQL server using Node.js?

For example: The following response represents the original data { "todo_id": 2, "todo_item": "brush your teeth", "scheduled_time": "2020-03-22T07:14:29.000Z", "user_id": 1, "is_done": { "type": "Buffer" ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Trouble with Bootstrap 5 Dropdown Menu failing to drop down

I am attempting to utilize a dropdown menu on my Wordpress site with Bootstrap, but it is not working as expected. If I manually add the class "show" to my dropdown-menu div, the menu displays, but the button does not function. These are the scripts being ...

creating arguments that have default values when using the new Function() syntax

How can I set default values for arguments when using the new Function method? let fileName = "fileone.js", args = [], options = {}; let ls = new Function('fileName', 'args', 'options', 'somefunctionorValue&apos ...

What is the most effective method for extracting properties from a struct and utilizing them as labels?

As I work on developing an iOS app, my focus is on creating a struct and populating an array with objects of that struct. The struct has two properties: flavors and descrip. My goal is to extract the flavor property from each object in the array and disp ...

Ways to execute various JavaScript functions based on the outcome of an AJAX request?

Currently, I am working on implementing some AJAX functionality where the actions in my JavaScript code depend on the response from the PHP file. Let me illustrate with an example: $.ajax({ type: 'POST', url: '/something.php', ...

Prevent iframe loading from occurring

I am currently working with an iframe where I upload files, but I am facing a challenge. How can I stop the loading process in the middle of it? I attempted to modify the src using a jQuery function attr(), however, it was not effective. Removing the entir ...

React component's object value is set to undefined upon clicking a button

Encountering a strange issue where the object values (strings) disappear when switching between components on button click. The values are passed as props from a single object and display fine initially, but become undefined after transitioning to another ...

The process involves transferring information from a specific div element to a database. This particular div element obtains its data after receiving an appended ID

It's a bit complicated, but I'm working on creating a tag system. I'm fetching data from a database with an AJAX call using the "@" symbol. Everything is working fine - the tags are being generated, but I'm having trouble retrieving and ...

Disappearing Data Mystery in ngFor Array

In my Angular 6 component, I have created a form for adding new users using an HTML table: user-add.component.html [...] <tbody> <tr *ngFor="let value of data.pos; let i = index"> <td><input matInput [(ngModel)]="value.us ...

Unable to convert JSON data from kafka to pandas format

Hello, I have the following code to consume Kafka data: bootstrap_servers = ['localhost:9092'] topicName = 'testapp5' consumer = KafkaConsumer (topicName, group_id ='group1',bootstrap_servers = bootstrap_servers) for msg i ...

"An error occurred when processing the JSON data, despite the JSON

Incorporating Ajax syntax for datatables and angularjs has been my current endeavor. Encountering an invalid JSON response with the following: self.dtOptions = DTOptionsBuilder.fromSource([{ "id": 860, "firstName": "Superman", "lastName": "Yoda" }]) How ...

Comparing the use of input parameters to pass information in node.js versus the use

I'm grappling with the concept of when to inject a response into a function or call a function and retrieve something from it. Specifically in Node.js. Do functions in Node.js actually return data, or is it primarily about passing arguments and utili ...

Adding a new column to a PySpark dataframe array

I am working with a Dataframe that has 2 columns | VPN | UPC | +--------+-----------------+ | 1 | [4,2] | | 2 | [1,2] | | null | [4,7] | My goal is to create a new column called "result" that combin ...

There was an issue with deserializing NewtonSoft Json due to a problem converting a string to a decimal value: /Date(1490721584000-0500

I am working on an ASP.Net MVC project where I'm using the NewtonSoft json deserializer to consume a json web service that sends dates in the /Date()/ format. The json I am receiving looks like this (showing just the first array element): [ { " ...

React Virtualized - Blank screen issue occurring because of continuous scrolling through a large list of ITSM items

I am currently working on a lengthy list of items and utilizing the react-virtualized library for this purpose. However, I have encountered an issue that needs addressing. https://i.stack.imgur.com/ROdjp.gif Upon attempting to scroll down for 2 seconds, ...

"Utilize the parent field while iterating through a for expression in JSL

Greetings, I am facing a challenging issue while trying to use jslt for JSON transformation. The input JSON data appears as follows: { "user_id": "001", "friends": [{ "friend_id": "002" ...

Having trouble with my Express app due to errors popping up because of the order of my routes

app.get('/campgrounds/:id/edit', async (req,res) =>{ const campground = await Campground.findById(req.params.id) res.render('campgrounds/edit', { campground }); }) app.get('/campgrounds/:id', async (req,res) =>{ ...