The JSON Array malfunctions by replacing the current array

I am having trouble with saving my JSON array to local storage because it keeps overwriting the existing array.

Take a look at my code:

Can you spot what I am doing incorrectly?

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

//STEP 2 - create an array 
var BasketContents = [];



//STEP 3 - create array of objects
BasketContents.push(Basket);

var count = BasketContents.length;

//   step 4 - reiterate through my array
for (i = 1; i <= BasketContents.length; i++) {
    BasketContents.push(Basket);
    localStorage.setItem('BasketContents', JSON.stringify(BasketContents[i]));
    if (i = BasketContents.length) {
        return;
    }
}


var lxs = JSON.parse(localStorage.getItem('BasketContents'));



console.log(lxs.length);

console.log(lxs);

The piece of code mentioned above is activated when a button is clicked, and it adds items to a shopping basket. The BasketContents.push function is used to add values to the basket incrementally.

Answer №1

One efficient method is to store the entire array in local storage like this:

localStorage.setItem('CartItems', JSON.stringify(CartItems));

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

Enhancing a Stripe customer object with additional metadata

While setting up a payment system using Stripe, I encountered an issue when trying to add metadata to the customer object. Specifically, I wanted to include my workspace id in the metadata property of the customer. However, upon executing the code below, I ...

The function of the React index key appears to be malfunctioning within the map function

I've been encountering issues despite using the index key and also attempted utilizing a unique id from JSON data, but unfortunately haven't found a solution yet. ERROR Warning: Each child in a list should have a unique "key" prop. const fa ...

What is the best way to implement the v-for loop in a Vue.js application?

I am currently working with a loop that contains four inputs. I am looking to assign separate id values from the loop to each of these inputs. How can I achieve this? click here for image click here for image While running a loop, I have only one input th ...

What is the reason behind event bubbling failing to function properly when CSS grid is utilized and elements are placed in the same cell

I am facing an issue with two grid children occupying the same cell and both having click event listeners. As per the concept of event bubbling, I expect both event listeners to be triggered when I click on the cell. const outer = document.getElementByI ...

"The Ajax function for replacing a div upon change event is not functioning properly

I am having an issue with my select box using the onchange event, <select class="form-control" onchange="getval(this.value,'<?php echo $prd->pr_id;?>','ajax<?php echo $key?>','<?php echo $key ?>')"&g ...

What is the method for utilizing a parameter in a protractor configuration file to select specific steps?

After reading this particular question, I attempted to implement the following: protractor test/features/protractor-conf.js --params.test_set=dev_test as well as protractor-conf.js: exports.config = { // ... specs: [browser.params.test_set+'/ ...

Top method for referencing HTML layout across various pages

Is there an optimal method for consistently calling an HTML structure from various pages? In my webapp, I have the same type of structure that needs to be called from different pages. For instance, I have a media management page displaying uploaded media ...

Creating dynamic nested objects using Javascript

In my quest to create serialized objects within the main object, I have come up with the concept of a solar system as an example of nesting. This allows me to access a variable by referencing it like this: universe.system1.planet4.x The hierarchy is univ ...

Leverage Contexts and Establish Context in React applications

I recently encountered some challenges while trying to implement React's context. As a newcomer to React, I would greatly appreciate any guidance on useful resources. Is it necessary for a component to be enclosed within a provider in order to access ...

Empty the password field

<input name="e_password" id="e_password" type="password" autocomplete="off" /> The password field above is causing some trouble as it gets automatically filled in Mozilla, but not in Chrome and IE11. This seems to be retaining values from previous a ...

Is it possible to use next.js to statically render dynamic pages without the data being available during the build process?

In the latest documentation for next.js, it states that dynamic routes can be managed by offering the route data to getStaticProps and getStaticPaths. Is there a way I can create dynamic routes without having to use getStaticProps() and getStaticPaths(), ...

Prevent the need to keep deleting text when entering data into selectize.js <select>_dropdown

I am working with a single choice <select> element that has been enhanced using selectize.js. This <select> element already has an option pre-selected as the current value. To change this value, users must: Click on the drop-down control, Pr ...

Developing a responsive navigation bar for mobile devices

Can anyone help me with creating a mobile navbar that shows the hamburger icon on smaller screens? I would like the links to appear in blocks when the icon is clicked. I attempted to make it using an SVG icon for the hamburger and setting the display to n ...

Send a pair of values using a set of two parameters

My current code is currently passing only one parameter value. However, I would like to modify it to pass two values with two parameters. This is my current code: <script> function getfilter(str){ document.getElementById("result"). ...

Update and change the property based on a condition in Ramda without the need for a lens

I am looking to modify properties for an object in ramda.js without using lenses. Given the data provided, I need to: If objects in array properties in a and b do not have the property "animationTimingFunction", then add the property key "easing" with a ...

Exploring deep within JSON data using jQuery or Javascript

I have a substantial JSON file with nested data that I utilize to populate a treeview. My goal is to search through this treeview's data using text input and retrieve all matching nodes along with their parent nodes to maintain the structure of the tr ...

Converting JSON data retrieved from a webpage into a List of objects using C#

Currently, I'm encountering issues while trying to read a JSON file. Here is the content of the file: { "players": [ { "Player": "124", "Last Name": "DE SANCTIS", "Position": "P", "Team": "ROM" }, { "Player ...

Eliminating redundancy in nested conditions

How can a nested conditional like the one below be optimized for improved performance and readability? To enhance efficiency, it would be beneficial to consolidate repetitive entries into a more practical function due to loops within many potential cases. ...

trouble with file reading into an array in C++

I'm facing an issue with my program that utilizes a 2D array to store values from a text file. The problem is that when the program prints out the array, all I see are zeros. What could be causing this error in my code? #include "stdafx.h" #include&l ...

AngularJS directive for attributes. Steps for adding a second attribute directive during compilation phase

I am interested in creating an attribute directive that adds an icon to a button when it is disabled. Click here to see a similar example on Fiddle In addition, I would like to include the ng-disabled directive during the compile process (with the value ...