Struggling to figure this one out...
I'm trying to remove a key/value pair, from my localStorage object. However, nothing gets removed. (I also don't have any errors).
I understand I can remove the key/value in question, by it's key name. Here's an example of the object:
bookMarksArray: [
{
"name": "reena",
"url": "brian"
},
{
"name": "joe",
"url": "ault"
}
]
And here's my code... I'm using event target to grab and match the key name, to the object index.
And then passing in key of that object index, into localStorage.removeItem()... What am I doing wrong?
list.addEventListener('click', event => {
if (event.target.classList.contains('js-delete-url')) {
const editName = event.target.parentElement.name.value;
const objIndex = bookMarksArray.findIndex(obj => obj.name === editName);
localStorage.removeItem(bookMarksArray[objIndex].name);
console.log('delete', bookMarksArray[objIndex].name);
}
});
Console prints this:
app.js:55 delete reena
Thank you!
LocalStoage saves the value in string format, so you have to stringify JSON object every time to save it in localStorage, we can solve this problem, please find below code snippet, useful in this scenario,
var updateStorage = function(filterName) {
var bookMarksArray= [{"name": "reena", "url": "brian"}, {"name": "joe", "url": "ault"}]
localStorage.setItem('nameList', JSON.stringify(bookMarksArray));
var items = JSON.parse(localStorage.getItem('nameList'));
var updatedList = items.filter(function(a) {
return a.name !== filterName;
});
localStorage.setItem('nameList', JSON.stringify(updatedList));
console.log(localStorage.getItem('nameList'));
// result [{"name":"reena","url":"brian"}]
};
updateStorage('joe');