Search code examples
javascriptif-statementlocal-storageshopping-cartsession-storage

Delete Session Storage - Shopping Cart Project


I hope this is a good question. I am working on a shopping cart project. I have been scouring the internet through different tutorials on shopping carts. I am attempting to write mine in Vanilla Javascript. I am having a problem with removing shopping cart items from session storage.

Below is what is currently in my session storage. As you can see it is an Array of objects.

[{"id":"8","name":"Candy 
Skull","price":"20000","image":"../images/candyskull- 
min.JPG","qty":"1"},{"id":"5","name":"Upsidedown 
House","price":"20000","image":"../images/upsidedownhouse- 
min.JPG","qty":"1"},{"id":"6","name":"Brooklyn 
Window","price":"30000","image":"../images/brooklynwindow- 
min.JPG","qty":"1"},{"id":"4","name":"Hand That 
Feeds","price":"40000","image":"../images/handthatfeeds- 
min.JPG","qty":"1"}]

I want to loop through the array and remove the matching object from the cart storage.

Below is the JS Code used to generate the .remove-from-cart buttons. As you can see it includes all the dataset information.

<td>
   <span class="remove-from-cart">
      <b data-id="${value.id}" data-name="${value.name}" data- 
      price="${value.price}" data-image="${value.image}" data- 
      qty="${value.qty}">X</b>
   </span>
</td>

To test the functionality of what I have done so far you can visit www.dancruzstudio.com/shop

The function that I can't get to work properly is the removeFromStorage() function. For some reason when comparing an object to the objects in the array I'm never getting back a true boolean value, even when there are items in the cart that should match. Where am I going wrong? I hope someone can help. Below is a copy of my JS code.

The method I am using is having an identical dataset value in the remove item button generated by JS and then parsing that dataset into an object and comparing it to the objects in the session storage array which is called shopItems inside the removeFromStorage() function. I hope this information is enough for someone to see my problem. Thank you in advance.

    // Remove item from DOM
    document.querySelector('#cart-list').addEventListener('click', 
    removeFromCart)

    function removeFromCart(e) {
    if(e.target.parentElement.classList.contains('remove-from-cart')) {
    //Remove from DOM
     e.target.parentElement.parentElement.parentElement.remove(); 

     //Remove from Session Storage
            removeFromStorage(e.target.dataset);
     }
     }

     // remove from Session storage
     function removeFromStorage(removedItem){

    let shopItems;
    if(sessionStorage['sc'] == null){
        shopItems = [];
    } else {
        shopItems = JSON.parse(sessionStorage['sc'].toString());
    }

    var compare = JSON.parse(JSON.stringify(removedItem))

    shopItems.forEach(function(item, index){

        if(compare === item){
            console.log(compare);
            console.log(item);
            // shopItems.splice(index, 1);
        }
    });
    sessionStorage['sc'] = JSON.stringify(shopItems);
    }

Solution

  • You can not compare objects like this.

    let a = {p:1};
    let b = {p:1};
    console.log(`a ===b ? ${a===b}`);

    If your objects are fairly simple you can try comparing their stringify representation:

    let a = {p:1};
    let b = {p:1};
    const compare = (x,y) => {
      return JSON.stringify(x) === JSON.stringify(y);
    }
    
    console.log(`a === b ?  ${compare(a,b)}`);

    or write your custom compare function (that may be challenging):

    Compare JavaScript objects

    Since your objects are decorated with an id, the easisest way would be to idntify them by that:

    let storage = [{"id":"8","name":"Candy Skull", "price":"20000","image":"../images/candyskull- min.JPG","qty":"1"},{"id":"5","name":"Upsidedown House","price":"20000","image":"../images/upsidedownhouse- min.JPG","qty":"1"},{"id":"6","name":"Brooklyn Window","price":"30000","image":"../images/brooklynwindow- min.JPG","qty":"1"},{"id":"4","name":"Hand That Feeds","price":"40000","image":"../images/handthatfeeds- min.JPG","qty":"1"}];
    
    let items = [{"id":"6","name":"Brooklyn Window","price":"30000","image":"../images/brooklynwindow- min.JPG","qty":"1"}, {"id":"5","name":"Upsidedown House","price":"20000","image":"../images/upsidedownhouse- min.JPG","qty":"1"}];
    const pluck = (acc, crt) => {
    acc.push(crt.id);
    return acc;
    };
    
    let storageIndexes = storage.reduce(pluck, []);
    let itemsIndexes = items.reduce(pluck, []);
    let removeIndexes = [];
    itemsIndexes.forEach(id => removeIndexes.push(storageIndexes.indexOf(id)));
    console.log('storage', storage);
    console.log('removed items', items);
    removeIndexes.sort().reverse().forEach(index => storage.splice(index,1));
    console.log('remaining storage', storage);