You cannot do this:
localStorage.removeItem(parseData[x]);
You need to either update the array you parsed, or create a new one, and then it back to JSON, and stringify to update the value in localStorage. Because localStorage can only store Strings, not Arrays or Objects.setItem
would be a nice way of doing it:filter
var jsonString = localStorage.getItem("addToFavs");
var arr = JSON.parse(jsonString);
// Filter to keep only those with a different ID than getID
arr = arr.filter(function(item) { return item['fav-name'] !== getID; });
// Store it back, stringified
localStorage.setItem("addToFavs", JSON.stringify(arr));
The reason you are running into an error is because, is not available in the scope of code ( and a reference error is thrown, when you try to access a variable that is not defined yet). In your case it lives on test because you are attaching it directly to localStorage.test object.localStorage
If you had used instead, you would not have come across the error.localStorage.removeItem(localStorage.test);
And it is not a good idea to set properties on the object directly.
Instead use localStorage to store data in local storage.setItem
var value = "good";
localStorage.setItem('test', value); // set the item
console.log(localStorage.getItem('test')); // retrieve the item
localStorage.removeItem('test'); // delete the item
In , setItem and getItem the first argument is the removeItem that you want to store or retrieve or delete from the storage. The name of the key in this case is key.test
should be done like that and not with delete operator:
localStorage.removeItem(key);
You could chain the promises to make sure it gets completed
$http.post("MyService/MyAction").then(function (res) {
if (res == true) {
window.localStorage.removeItem(myToken);
//window.localStorage.getItem(myToken) returns null in here.
}
})
.then(
window.location = baseURL + 'Login.aspx';
)
.error(function () {
//some stuff
});
All the answers were right but you have to :
So :
1.
var items = JSON.parse(localStorage.getItem("items")); // updated
2.
for (var i =0; i< items.length; i++) {
var items = JSON.parse(items[i]);
if (items.itemId == 3) {
items.splice(i, 1);
}
}
3.
items = JSON.stringify(items); //Restoring object left into items again
4.
localStorage.setItem("items", items);
Parsing to JSON and storing it as string is kinda annoying, but that's the way localStorage works.
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));