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.