从localStorage Angular中删除数组对象

时间:2015-05-20 12:08:36

标签: arrays angularjs local-storage

在我的Ionic Framwork应用程序中,我有一个存储在角度localStorage中的购物车数组 像这样

localStorage.setItem('mycart', JSON.stringify(items));

然后我像这样检索localStorage数组

var cart_items = JSON.parse(localStorage.mycart);

输出

[{"id":"1","item_name":"pepsi","qty":"2"},{"id":"2","item_name":"coke","qty":"2"},
{"id":"3","item_name":"fanta","qty":"3"}]

我正在尝试使用以下代码删除产品项目。但它不起作用,它会删除数组中的整个项目

for ( var i = 0; i < cart_items.length; i++ ) {
    if ( cart_items[i].id === $removeId ) { //
       cart_items.splice(i,1); 
    }
}
localStorage.mycart= JSON.stringify(cart_items );

删除数组中的所有项目

1 个答案:

答案 0 :(得分:0)

这最终对我有用

var cart_items = JSON.parse(localStorage["mycart"]);
for (i=0;i<cart_items.length;i++)
  if (cart_items[i].id == 'id_1') cart_items.splice(i,1);
  localStorage["mycart"] = JSON.stringify(cart_items);