How do I check and update an array of JSON objects
hi guys
I am trying to create a shopping basket in a JSON array and an array to be stored in the localStorage.
I want to
1. Check if exists
2.
Update the array based on ProductID
3. If it does not exist then
add new values to the array
4. Then update the localstorage.
Currently my code does not update e.g. 1 + 1 is 11 instead of 2. What am i doing wrong
SEcondly the array appears to be sub arrays instead of updating it
- var Basket = { ProductID: product, Quantity: quantity }; // create shopping basket values
- //STEP 2 - create an array
- //
- var BasketContents = []; // EMPTY the contents
-
-
- // step 3 - update contents
- if (localStorage.BasketContents) //check contents
- {
-
-
-
- const update = JSON.parse(localStorage.getItem('BasketContents'));
-
-
- update.forEach(x => {if (x.ProductID == product)
- {
- int count = x.Quantity + quantity;
- x.Quantity = count;
- BasketContents.push(update);
- localStorage.removeItem('BasketContents');
- localStorage.setItem('BasketContents', JSON.stringify(BasketContents));
- return;
- }
- else
- {
- BasketContents.push(Basket);
-
- localStorage.removeItem('BasketContents');
- localStorage.setItem('BasketContents', JSON.stringify(BasketContents));
- return;
- }
- });