如何删除存储在本地存储中的数据?

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

{"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删除缓存中的数据

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

所以结果是这样的:

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

我该怎么做?

您可以使用array#splice()从数组中删除元素。 使用JSON.parse()localStorage获取对象,然后遍历数组并通过比较它们的id删除元素,然后将结果存储回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)); 

您需要检索对象修改它,然后将其再次存储在本地存储中,

 var retrievedObj = JSON.parse(localStorage.getItem("cartCache")); retrievedObj.dataCache[0].id = 53; localStorage.setItem('cartCache', JSON.stringify(retrievedObj)); 

在这里,您将使用示例解决方案https://jsfiddle.net/rhwf1j5g/1/

 var data = {"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"}]}; var removeid = 20; var newData = $.grep(data.dataCache, function(value) { return value.id != removeid; }); console.log(newData); 
  

你可以试试这个:

 const filtered = JSON.parse(localStorage.cartCache) .dataCache.filter(filteredObj => filteredObj.id !== 20); localStorage.cartCache = JSON.stringify({ "dataCache": filtered }); 

我在这里简单地做的是使用JSON对象的parse()方法将localStorage的项目转换为JS对象。
我通过直接访问dataCache而不是将其分配给变量来链接调用,然后我链接filter()调用,因为dataCache的返回值是一个数组。 我正在过滤id不等于20
我将结果分配给filtered变量,之后我调用stringify()传递filtered结果。
最后,我将它保存到localStorage

 // LocalStorage Mock let localStorageMock = (function() { var storage = {}; return { setItem: function(key, value) { storage[key] = value || ''; }, getItem: function(key) { return storage[key] || null; }, removeItem: function(key) { delete storage[key]; }, get length() { return Object.keys(storage).length; }, key: function(i) { var keys = Object.keys(storage); return keys[i] || null; } }; })(); Object.defineProperty(window, 'localStorage', { value: localStorageMock }); // Code you need localStorage.cartCache = JSON.stringify({"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"}]}); const filtered = JSON.parse(localStorage.cartCache) .dataCache.filter(filteredObj => filteredObj.id !== 20); localStorage.cartCache = JSON.stringify({ "dataCache": filtered }); console.log(JSON.parse(localStorage.cartCache));