使用javascript从本地存储对象内的数组中删除项目

时间:2016-09-27 12:52:49

标签: javascript local-storage

我有localStorage['cart'],其中有数组'产品'。 来自localStorage.getItem('cart')的检索数据类似于

{"products":
[
    {
    "id":"01",
    "name":"Product Name 01",
    "price":"Product Price 01",
    "image":"Product Imagem 01"
    },
    {
    "id":"02",
    "name":"Product Name 02",
    "price":"Product Price 02",
    "image":"Product Imagem 02"
    },
]}

我需要在onclick=事件中使用products删除id数组中的特定项目。

修改

var json = JSON.parse(localStorage["cart"]);
for (i=0; i < x; i++){
          if (json.products.[i].id == id){
            json.splice(i,1);
        }
      }

x是json.products lenght。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是基本的想法。向您展示如何从localStorage解析对象 怎么写回来。

(function() {
  //prime cache
  var obj = {
    "products": [{
      "id": "01",
      "name": "Product Name 01",
      "price": "Product Price 01",
      "image": "Product Imagem 01"
    }, {
      "id": "02",
      "name": "Product Name 02",
      "price": "Product Price 02",
      "image": "Product Imagem 02"
    }]
  };
  localStorage.setItem("cart", JSON.stringify(obj));

}());

function removeItem(id) {
  var index = -1;
  var obj = JSON.parse(localStorage.getItem("cart")) || {}; //fetch cart from storage
  var items = obj.products || []; //get the products
  for (var i = 0; i < items.length; i++) { //loop over the collection
    if (items[i].id === id) { //see if ids match
      items.splice(i, 1); //remove item from array
      break; //exit loop
    }
  }
  localStorage.setItem("cart", JSON.stringify(obj)); //set item back into storage
}

console.log(localStorage.cart);
removeItem("01");
console.log(localStorage.cart);