如果我是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"}],"expired":"2017-08-28T03:55:21.521Z"}
我想通过索引数组
删除缓存中的数据例如,当我删除索引数组= 0时,结果如下:
{"dataCache":[{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}]}
另一个例子,当我删除索引数组= 1时,结果如下:
{"dataCache":[{"id":20,"quantity":1,"total":100000,"request_date":"27-08-2017 20:31:00"}]}
我该怎么做?
我试着这样:
var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache")
delete retrievedObj['dataCache'][deleteIndex];
似乎这不是正确的方式
答案 0 :(得分:4)
localStorage.getItem("cartCache")
会返回两个对象 - dataCache 和过期。如果您要删除 dataCache 的元素n
,请将其删除
localStorage.getItem("cartCache").dataCache.splice(n,1);
使其适合您的代码:
var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache");
retrievedObj.dataCache.splice(deleteIndex,1);
然后再次console.log
您的localStorage,您就会看到该元素被移除。
答案 1 :(得分:1)
您可以使用splice
从数组中删除项目
// Clearing all localStorage value. No need to use below line in your code
localStorage.clear();
// to be stored object
var x = {
"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"
}],
"expired": "2017-08-28T03:55:21.521Z"
}
// Initially storing it in local storage using JSON.stringify
localStorage.setItem('storeData', JSON.stringify(x));
// Once stored retrieving the value using JSON.parse
var getItem = JSON.parse(localStorage.getItem('storeData'));
// setting the dataCache with new array. The new array will be created as splice is used. splice is used to remove an item from array,
//0 is the index of the array, while second parameter 1 is to represent how many item to be removed starting from 0 ndex
getItem.dataCache = getItem.dataCache.splice(0, 1);
console.log(getItem); // the modified object
// after operation setting it to local storage
localStorage.setItem('storeData', JSON.stringify(getItem))
答案 2 :(得分:0)
关键字“删除”仅在retrieveObj中删除deleteIndex,它不会更新您的localStorage值。为了更新localStorage使用:
var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache")
delete retrievedObj['dataCache'][deleteIndex];
localStorage.setItem("cartCache", retrieveObj)