mercredi 26 décembre 2018

Compare object to object in array for ShopCart Item removal

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 trouble with removing shopping cart items from session storage.

To test the functionality of what I have so far you can visit http://bit.ly/2ENK7ZA

The function that I cant get to work properly is the removeFromLocalStorage() function. For some reason when comparing an object to the object in array Im not getting back any true value even when there are many items in the cart. What am I doing wrong? I hope someone can help. Below is a copy of my JS code.

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

 'use strict';

    const addToCartButtons = document.querySelectorAll('.shop-btn');
    let shopCart = [];



    ouputCart();

    // add listeners to cart buttons
    addToCartButtons.forEach(addToCartButton => {
    addToCartButton.addEventListener('click', () => {
        const productInfo = addToCartButton.dataset; // Get data set
        productInfo.qty = 1;    //Set quantity
        var itemInCart = false; // Set item in cart boolean


        shopCart.forEach(function(cartItem, index){  //Check if item 
in 
    cart
            if(cartItem.id == productInfo.id) {
                cartItem.qty = parseInt(cartItem.qty) + 
    parseInt(productInfo.qty);
                itemInCart = true;
            }

        });

        if(itemInCart === false) {
            shopCart.push(productInfo);
        }
        sessionStorage['sc']= JSON.stringify(shopCart);
        ouputCart();
    })
    });



    function ouputCart() {
    if (sessionStorage['sc'] != null) {
        shopCart = JSON.parse(sessionStorage['sc'].toString());

    }

    var holderHTML = '';
    var totalPrice = 0;
    var totalItems = 0

    shopCart.forEach(function(value, index){
        var subTotalPrice = value.qty * value.price
        totalPrice += subTotalPrice;
        totalItems = parseInt(totalItems) + parseInt(value.qty);
        holderHTML += `<tr>
                        <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>
                        <td> 
                            <div class="modal__image-container">
                                <img src="${value.image}" alt="dan 
cruz 
    painting" class="modal__image"/>
                            </div> 
                        </td>
                        <td>
                            <span>${value.name}</span>
                        </td>
                        <td>
                            ${value.qty}
                        </td>
                        <td> 

    ${numberWithCommas(formatMoney(subTotalPrice))}
                        </td>
                       </tr>`
    });


    document.querySelector('#cart-list').innerHTML = holderHTML;
    document.querySelector('.cart-total-items').innerText = totalItems;
    document.querySelector('.cart-total-price').innerText = 
    numberWithCommas(formatMoney(totalPrice));

    }

    function formatMoney(n) {
    return (n/100).toFixed(2);
    }


    function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }


    // Remove item from DOM

    document.querySelector('#cart-list').addEventListener('click', 
    removeFromCart)

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

     //Remove from Local Storage
            removeFromLocalStorage(e.target.dataset);
     }
     }

     // remove from local storage
     function removeFromLocalStorage(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);
    }



    //// Modal Open/Close

    const viewCart = document.querySelector('.shop__cart-reminder');
    const modal = document.querySelector('.modal');
    const modalDisplay = document.querySelector('.modal__container');
    const closeModal = document.querySelector('.modal__close');
    const keepShopping = document.querySelector('.keep-shopping');

    viewCart.addEventListener('click', function(){
    modal.style.display = 'block';
    modalDisplay.style.display = 'block';
    })

    modal.addEventListener('click', function(){
    modal.style.display = 'none';
    modalDisplay.style.display = 'none';
    })

    closeModal.addEventListener('click', function(){
    modal.style.display = 'none';
    modalDisplay.style.display = 'none';
    })

    keepShopping.addEventListener('click', function(){
    modal.style.display = 'none';
    modalDisplay.style.display = 'none';
    })

Aucun commentaire:

Enregistrer un commentaire