How to delete a JSON within an Array in localStorage()

Asked

Viewed 60 times

-5

I’m creating an app for annotations and I would like to be able to delete the respective note, when the user clicks, I created this function but it is not returning anything to my localStorage(), I wonder if there is any other alternative for me to delete the JSON inside the Note Array.

My code:

function deleteNote(noteId) {             
    let jsonData = localStorage.getItem("notes")

    let data = JSON.parse(jsonData)                
        
    for (item in data) {          
        for (i=0; i < data[item].length; i++) {
            if(data[item][i].id == noteId){
                data[item].splice(i, 1)
                break;
             }
         }
     }        
     localStorage.setItem("notes", JSON.stringify(data))                        
} 

Items within the localStorage(): Meu localStorage

  • What code did you attach to the question is doing? Was it to remove a note? If so, wouldn’t a parameter be missing id?

1 answer

1


You should pass an argument like id or noteId to know which id to remove

function deleteNote(id) {             
  const data = JSON.parse(localStorage.getItem('notes')).filter(item => item.noteId !== id)
  localStorage.setItem('notes', JSON.stringify(data))
}
  • 2

    Thank you, that’s what I needed :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.