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

时间:2018-12-26 17:07:03

标签: javascript if-statement local-storage shopping-cart session-storage

我希望这是一个好问题。我正在从事购物车项目。我一直在通过购物车上的不同教程来搜寻互联网。我试图用Vanilla Javascript编写我的。我在从会话存储中删除购物车商品时遇到问题。

以下是我的会话存储中当前的内容。如您所见,它是一个对象数组。

[{"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"}]

我想遍历数组并从购物车存储中删除匹配的对象。

下面是用于生成.remove-from-cart按钮的JS代码。如您所见,它包含所有数据集信息。

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

要测试我到目前为止所做的功能,您可以访问www.dancruzstudio.com/shop

我无法正常工作的函数是removeFromStorage()函数。由于某种原因,将对象与数组中的对象进行比较时,即使在购物车中有应匹配的项目时,我也永远不会找回真正的布尔值。我要去哪里错了?我希望有人能帮帮忙。下面是我的JS代码的副本。

我正在使用的方法是在JS生成的删除项按钮中具有相同的数据集值,然后将该数据集解析为一个对象,并将其与会话存储数组中的对象进行比较,该存储数组在removeFromStorage()内部称为shopItems功能。我希望这些信息足以使某人看到我的问题。预先谢谢你。

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

1 个答案:

答案 0 :(得分:0)

您不能比较这样的对象。

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

如果您的对象非常简单,则可以尝试比较它们的字符串表示形式:

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

或编写您的自定义比较功能(可能会很困难):

Compare JavaScript objects

由于您的对象都装饰有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);