首页 > 解决方案 > 如何从索引和键更新本地存储对象值

问题描述

我的项目需要这个解决方案。它对我来说非常重要。我想从我的购物车应用程序的本地存储中使用键和索引更新对象值。

(购物车中产品数量的减少按钮)

示例。

function decreaseQuantity(index) {
  var oldQty = localStorage.cart[index].quantity;
  var newQty = oldQty - 1;
  localStorage.setItem(cart[index].quantity, newQty);
}

标签: javascriptarraysobjectlocal-storage

解决方案


您不能将复杂对象存储在 中localStorage,只能将数据存储为string

如果要将购物车对象存储到locaStorage,则需要使用将其序列化为字符串 JSON.stringify并将其存储如下。

window.localStorage.setItem('cart', JSON.stringify(cart));

注意:这里的“购物车”是关键。

要返回、更改并存储回来,您需要执行以下操作。

 var data = window.localStorage.getItem('cart');
        if (data != null) {
            let cart= JSON.parse(data);
              cart[index].quantity = cart[index].quantity -1;
             window.localStorage.setItem('cart', JSON.stringify(cart));

        } 

推荐阅读