如何删除存储在本地存储中的数据? [英] How can I remove data which is stored in local storage?

查看:471
本文介绍了如何删除存储在本地存储中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我是console.log(localStorage.getItem(cartCache)),结果如下:

If I console.log(localStorage.getItem("cartCache")), the result like this :

{"dataCache":[{"id":20,"quantity":1,"total":100000,"request_date":"27-08-2017 20:31:00"},{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}]}

我想通过id删除缓存中的数据

I want to remove the data in the cache by id

例如,我删除id = 20,它将删除id = 20 in缓存

For example, I remove id = 20, it will remove id = 20 in the cache

所以结果是这样的:

{"dataCache":[{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}]}

我该怎么办?

推荐答案

您可以使用 array#splice()从数组中删除元素。使用 JSON.parse() localStorage 中获取对象,然后遍历数组并删除元素比较他们的id然后将结果存储回localStorage。

You can use array#splice() to delete an element from an array. Use JSON.parse() to get the object from the localStorage and then iterate through your array and delete the elements by comparing their id and then store the result back to localStorage.

var str = localStorage.getItem('cartCache'); 
var cartCache = JSON.parse(str);
var idToRemove = 20;
cartCache.dataCache.forEach((obj,i) => {
  if(obj.id === idToRemove)
    cartCache.dataCache.splice(i,1);
});
localStorage.setItem('cartCache', JSON.stringify(cartCache));

这篇关于如何删除存储在本地存储中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆