本文介绍了LocalStorage-按值而不是键删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,所以我在LocalStorage中有这样的JSON:
Ok so I have a JSON like this stocked in LocalStorage :
[{"pseudo":"Lucia","id":2},{"pseudo":"Romain","id":1}]
我搜索了如何删除一项,但只找到了这一点:
I searched how I can remove one item and I only find this :
storage.removeItem(keyName);
但是,如果我错了,请纠正我,如果我这样做,如果我执行storage.removeItem(pseudo),则会删除keyName为"pseudo"的所有值.
But, correct me if I am wrong, if I use this will remove all the value with keyName "pseudo" if I do storage.removeItem(pseudo);
如何仅从json中删除{"pseudo":"Romain","id":1}
并保留{"pseudo":"Lucia","id":2}
?
How can I only remove {"pseudo":"Romain","id":1}
from the json and keep {"pseudo":"Lucia","id":2}
?
谢谢.
推荐答案
localstorage仅支持字符串值,因此您需要解析数据.
localstorage only supports string values, so you need to parse data.
var storedNames = JSON.parse(localStorage.getItem("keyName"));
// here you need to make a loop to find the index of item to delete
var indexToRemove = 1;
//remove item selected, second parameter is the number of items to delete
storedNames.slice(indexToRemove, 1);
// Put the object into storage
localStorage.setItem('keyName', JSON.stringify(storedNames));
这篇关于LocalStorage-按值而不是键删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!