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);
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);
How can I only remove {"pseudo":"Romain","id":1}
from the json and keep {"pseudo":"Lucia","id":2}
?
Thank you.
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);
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);
How can I only remove {"pseudo":"Romain","id":1}
from the json and keep {"pseudo":"Lucia","id":2}
?
Thank you.
Share Improve this question edited Sep 7, 2016 at 12:56 DionysoSong asked Sep 7, 2016 at 10:05 DionysoSongDionysoSong 8071 gold badge14 silver badges29 bronze badges 2- That is the issue with storing plex objects in localstorage. You will have to read the entire JSON object, parse it, modify it, stringify it then save the modified object. You should be looking into IndexDB if your wanting plex data objects and querying. – ste2425 Commented Sep 7, 2016 at 10:09
-
(1.) Get the data from
LocalStorage
(2.) Parse it (3.) Splice theobject
from parsed array (4.) Againstringify
the data (5.) Assign it back toLocalStorage
– Rayon Commented Sep 7, 2016 at 10:09
3 Answers
Reset to default 2localstorage 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 es with a length so you know how many values are being stored and a method key which lets you find a key at an index.
function removeLocalStorageValues(target) {
let i = localStorage.length;
while (i-- > 0) {
let key = localStorage.key(i);
if (localStorage.getItem(key) === target) {
localStorage.removeItem(key);
}
}
}
localstorage only supports string values, so you need to parse data. ( replaced slice to splice )
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.splice(indexToRemove, 1);
// Put the object into storage
localStorage.setItem('keyName', JSON.stringify(storedNames));