The_Ogre
The_Ogre

Reputation: 127

Removing a nested item from the localStorage in javascript

I have certain items on a page where by, when 'addToCart' is clicked, the respective item is saved in the local storage from which it is retrieved and displayed in the cart. The format with which they are sent to the local storage is cartItems={[product.title]:product} which is then stored using the line localStorage.setItem('productsInCart',JSON.stringify(cartItems)); When for instance an item called Jack Daniels 1L is tapped and consequently stored in the local storage, I get a table the that looks like below in the local storage:

Key Value
    
cartNumbers 1
productsInCart  {"Jack Daniels 1L":{"title":"Jack Daniels 1L","cost":3850,"cartConts":1}}
totalCost   3850

Once the product is displayed in the cart, there's a delete button which can be used to delete it, especially from the local storage i.e I wish to delete the following entry from the local storage {"Jack Daniels 1L":{"title":"Jack Daniels 1L","cost":3850,"cartConts":1}}. Below is a function called when the delete button has been tapped that I hoped would have worked but in vain:

function removeCartItem(event){

    var buttonClicked = event.target;
    
     if (buttonClicked) {
        var current = buttonClicked.parentElement.parentElement;
        var title = current.querySelectorAll('.cart-item-title')[0].innerText;
        var cartItems = localStorage.getItem('productsInCart');
            cartItems = JSON.parse(cartItems)

        if (cartItems) {
            var itemKeys = Object.keys(cartItems);
                for (var i = 0; i < itemKeys.length; i++) {
                    var key = itemKeys[i]
                    console.log(key)//in this case prints: Jack Daniels 1L, as desired.
                    if (title === key ) {
                        localStorage.removeItem(key)
                    }
                }
        }
    }
} 

What is the best way to proceed?

Upvotes: 3

Views: 1399

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206593

There's no LocalStorage key to remove (in your specific case) - since your only LS key is your actual productsInCart in its entirety, which is holding pretty much all the cart data.
You simply want to delete a property/value from an object. Therefore, use Object's delete.
After deleting your Object entry, simply store back into LS the entire stringified productsInCart Object data.

// Get <button> and UID
const EL_button = event.currentTarget;
const id = EL_button.closest("[data-id]"); // i.e: "245"

// Parse LS 
const cartItems = JSON.parse(localStorage.productsInCart || "{}");  // Object

// Check if exists
if (cartItems.hasOwnProperty(id)) {
  // Exists in LS cart! 
  // Delete it!
  delete cartItems[id];
  // Update LS:
  localStorage.productsInCart = JSON.stringify(cartItems);
  // Do something with that button:
  EL_button.textContent = "Add to cart";
}

The above code is given a HTML like i.e:

<div data-id="245">
  Juicy Peach 3dl - 2$
  <button type="button" data-id="245">Remove from cart</button> 
</div>
<div data-id="455">
  Energy overflow 1L - 5$
  <button type="button" data-id="455">Remove from cart</button> 
</div>

and a JSON data like i.e:

{
  "245" : {"id":"245", "name":"Juicy Peach 3dl", "price":"2", "cartConts":1},
  "455" : {"id":"455", "name":"Energy overflow 1L", "price":"5", "cartConts":0},
}

Upvotes: 4

Related Questions