Update/Edit JSON in localStorage() with Java Script

Asked

Viewed 106 times

1

I’m developing an app for annotations in Javascript, and would like to edit an annotation saved in JSON on localStorage. This my code is returning only 1 (one) single object and overwrite the others that are stored, I wonder how I can edit only the informed by the user.

My code:

function saveEditedNote(title, text) {
    let notesEdit = JSON.parse(localStorage.getItem("notes"))
    let note = {
        noteTitle : title,
        noteText : text
    }
    localStorage.setItem("notes", JSON.stringify(note))            
}

My localStorage:

localStorage()

  • yes will overwrite even retrieving the previous values in the variable notesEdit does nothing with it and arrow a new object in "Notes"

  • if I set a new object, the old one will still be present in Storage, I would like to edit the object or else, remove it and add the "edited" object in localSotrage

  • was what I commented, add the new "note" to the "notesEdit" and set the "notesEdit"

1 answer

1


Maybe this can help you:

You can also pass the id and the guy as a parameter of your annotation present in your Storage for function saveEditedNote, and so filter it by passing the values of your "edited" annotation to the Array from Storage, right after, set your item in the localStorage.

function saveEditedNote(id, type, title, text) {
    let notesEdit = JSON.parse(localStorage.getItem("notes"))
        .filter(item => item.noteId !== id)

    notesEdit.push({
        noteTitle: title,
        noteText: text,
        noteType: type,
        noteId: id
    })
    localStorage.setItem("notes", JSON.stringify(noteEdit))            
}
  • 1

    Thank you! , that’s what I needed!

Browser other questions tagged

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