0

Solved Now - sessionStorage->array->make New Array without item -> back to sessionStorage

This is driving me nuts, and yes have looked all day for a solution.

I'm trying to remove item from the sessionStorage. But just one item. I can find the item, just can't remove it. Any help would be great, Thanks

function removeCartItem(key) {
    if (sessionStorage.getItem('shopping-cart')) {
        var IsItemThere = false;
        var shoppingCart = JSON.parse(sessionStorage.getItem('shopping-cart'));
        shoppingCart.forEach(function(item) {
            var cartItem = JSON.parse(item);
            if(cartItem.key === key){
                IsItemThere = true;
            }
        });
        if(IsItemThere == true){
            var cartArray = new Array();
            shoppingCart.forEach(function(item) {
                var cartItem = JSON.parse(item);
                if(cartItem.key != key){
                    cartItem = {
                        key: cartItem.key,
                        id: cartItem.id,
                        productName: cartItem.productName,
                        price: cartItem.price,
                        quantity: cartItem.quantity
                    };
                    var cartItemJSON = JSON.stringify(cartItem);
                    cartArray.push(cartItemJSON);
                }
            });
        }
        sessionStorage.removeItem('shopping-cart');
        var cartJSON = JSON.stringify(cartArray);
        sessionStorage.setItem('shopping-cart', cartJSON);
    }
}

This is how each item look like, and yes, the alert does popup {"key":14759,"id":"1","productName":"Sample Product 1","price":"12.77","quantity":"1"}

11
  • what is the error you are getting ? Commented Dec 14, 2022 at 15:06
  • make sure 'TheCart' (.getItem('TheCart'));) is equal to item you're passing in .removeItem(item) Commented Dec 14, 2022 at 15:07
  • stackoverflow.com/questions/38748298/… Commented Dec 14, 2022 at 15:07
  • Do you have an item key in your Session Storage? It seems you only have the key "TheCart". shoppingCart is the object that has item, not the Session Storage. In your Session Storage, you need to set the updated JSON, not remove something. Commented Dec 14, 2022 at 15:08
  • I'm a bit confused; is the item stored in an array in session storage, or is it stored separately? You appear to be removing a separate item (and not modifying the cart array, or storing it back into session storage). Commented Dec 14, 2022 at 15:08

1 Answer 1

0

Solved Now - sessionStorage->array->make New Array without item -> back to sessionStorage

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.