将具有相同ID的项目一起添加到本地存储中

时间:2019-02-28 19:52:32

标签: javascript local-storage

我正在努力在本地存储中创建“添加到购物车”选项,以发送到我们的ESP以放弃购物车。我将这些物品一旦添加到购物车中,并将其添加到“本地存储”中,按键为:购物车。购物车创建一个数组,每次添加产品时,都会将一个新对象插入到数组中。我现在要弄清楚的是,当再次添加具有相同sku的项目时,如何获取它以更新已经存在的对象,而不是将另一个对象插入数组。

// Try to retreive the count of shopping cart items from localStorage
var cartCounter = localStorage.getItem('cartCounter');

if (cartCounter != null) {
  // We already have at least one item in localStorage so increment the counter
  cartCounter = parseInt(cartCounter) + 1
}
else {
  // No items in localStorage so initialize the counter
  cartCounter = 1;
}

// Get the data layer push
var pr = {{DL - Add To Cart}};

// Store product sku, name, and price in localStorage
// Using string format product[cartCounter]attribute for the key
localStorage.setItem('product' + cartCounter + 'sku', pr.fullProductSKU);
localStorage.setItem('product' + cartCounter + 'name', pr.name);
localStorage.setItem('product' + cartCounter + 'price', pr.price);
localStorage.setItem('product' + cartCounter + 'quantity', pr.quantity);

var addItem = function (sku, qty, price) {
    var oldItems = JSON.parse(localStorage.getItem('cart')) || [];        
    var newItem = {
        'product-sku': sku,
        'product-qty': qty,
        'product-price': price
    };        
    oldItems.push(newItem);        
    localStorage.setItem('cart', JSON.stringify(oldItems));
};

console.log(JSON.parse(localStorage.getItem('cart')));
addItem(pr.fullProductSKU, pr.quantity, pr.price);

这是我得到的输出,非常好,但是前两个项目具有相同的SKU,因此我希望将其合并为1个对象,数量显示2,价格也要更新。

[{product-sku: "965000070", product-qty: 1, product-price: 40.99}
 {product-sku: "965000070", product-qty: 1, product-price: 40.99}
 {product-sku: "965000244", product-qty: 1, product-price: 48.99}]

这就是我要输出的内容:

[{product-sku: "965000070", product-qty: 2, product-price: 81.98}
 {product-sku: "965000244", product-qty: 1, product-price: 48.99}]

1 个答案:

答案 0 :(得分:1)

您可以只查看从cart检索到的数组,并检查产品是否已包含在内,然后更新数量。例如,find可用于该查找:

var addItem = function (sku, qty, price) {
    var oldItems = JSON.parse(localStorage.getItem('cart')) || [];
    var match = oldItems.find(function (item) {
        return item['product-sku'] === sku;
    });
    if (match) {
        match['product-qty'] += qty;
        match['product-price'] += price;
    } else {
        var newItem = {
            'product-sku': sku,
            'product-qty': qty,
            'product-price': price
        };
        oldItems.push(newItem);
    }
    localStorage.setItem('cart', JSON.stringify(oldItems));
};