Reputation: 67
I have an array stored in localStorage. When a button is clicked, I would like the item in the array to be removed and again saved into localStorage. Here's what I mean.
var greetings = ["Hello", "Hi", "Sup", "Hey"]
localStorage.setItem("greetings", JSON.stringify(greetings))
function remove() {
//remove "hi" How do I do this?
}
<button onclick="remove()">Remove</button>
Upvotes: 0
Views: 1714
Reputation: 25
I think You want this.
Click here
Hope it work or it would help little bit.enter code here
Upvotes: 0
Reputation: 1002
You need to get the items from the array with localStorage.getItem('greetings') then you need to parse the string with JSON.parse(array) as localstorage items are always strings. Then you need to filter out your preferred string: array.filter(item => item !== 'Hello') and then finally update the localstorage: localStorage.setItem("greetings", JSON.stringify(updatedArray)
const greetings = ["Hello", "Hi", "Sup", "Hey"];
localStorage.setItem("greetings", JSON.stringify(greetings));
function remove() {
const greetings = JSON.parse(localStorage.getItem("greetings"));
const filtered = greetings.filter(item => item !== 'Hello');
localStorage.setItem("greetings", JSON.stringify(filtered));
}
Upvotes: 1