简体   繁体   English

删除会话存储-购物车项目

[英]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. 我试图用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. 以下是用于生成.remove-from-cart按钮的JS代码。 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 要测试到目前为止我所做的功能,请访问www.dancruzstudio.com/shop

The function that I can't get to work properly is the removeFromStorage() function. 我无法正常使用的功能是removeFromStorage()函数。 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. 下面是我的JS代码的副本。

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. 我正在使用的方法是在JS生成的删除项按钮中具有相同的数据集值,然后将该数据集解析为一个对象,并将其与会话存储数组中的对象进行比较,该存储数组在removeFromStorage()函数内部称为shopItems。 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);
    }

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 比较JavaScript对象

Since your objects are decorated with an id, the easisest way would be to idntify them by that: 由于您的对象是用ID装饰的,所以最简便的方法是通过以下方法对它们进行标识:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM