frankfurt
frankfurt

Reputation: 153

how to remove last value localstorage?

I want to ask you something guys, I hope you can help. I am confused how to remove last value from localstorage? the localstorage value I have as below, I want to delete the 'Sprints' value. If i use localStorage.removeItem('tags'), all values ​​will be deleted right? but I just want remove the last value. please help me, cause i'm confused

enter image description here

Upvotes: 1

Views: 554

Answers (1)

Phil
Phil

Reputation: 164897

localStorage is only capable of storing string values so what you've got there is an array, serialised to JSON.

To remove elements from it, you'll need to

  1. Parse the string as JSON to an array
  2. Remove the item
  3. Stringify the array and put it back in localStorage
const tags = JSON.parse(localStorage.tags ?? "[]")
localStorage.tags = JSON.stringify(tags.slice(0, -1))

You can of course single-line this

localStorage.tags = JSON.stringify(JSON.parse(localStorage.tags ?? "[]").slice(0, -1))

Upvotes: 3

Related Questions