1

I have an object stored in localStorage.

let ship = {
    name: "black pearl",
    captain: "Jack Sparraw"
  };

 localStorage.setItem("ship", JSON.stringify(ship));

enter image description here

Now I want to change "name" to a new name. How to achieve it using Javascript?

(The following code does not work, but it gives an idea what I want to do)

 localStorage.setItem(localStorage.getItem("ship").name, "newName");
Ning
  • 499
  • 1
  • 4
  • 16
  • `localStorage.setItem('ship', JSON.stringify({...JSON.parse(localStorage.getItem('ship')), name: 'newName'}))` – The Fool Sep 29 '19 at 12:44
  • I added an answer for you here: https://stackoverflow.com/questions/37052087/how-do-i-update-localstorage-items/58155423#58155423 – Cat Sep 29 '19 at 13:00

1 Answers1

4

You retrieve the JSON, parse it, update the object you get from parsing it, stringify the result, and store that result:

const ship = JSON.parse(localStorage.getItem("ship"));
ship.name = "newName";
localStorage.setItem("ship", JSON.stringify(ship));

If you want to do it all in one line (although I don't recommend it, it's harder to read, maintain, and debug that way; leave minification to minifiers):

localStorage.setItem("ship", JSON.stringify(Object.assign(JSON.parse(localStorage.getItem("ship")), {name: "newName"})));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @Ning - Thanks for catching that! *(I think your edit was rejected by the reviewers because you only fixed one place but it needed fixing in two.)* – T.J. Crowder Sep 30 '19 at 05:58