2

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");
2
  • localStorage.setItem('ship', JSON.stringify({...JSON.parse(localStorage.getItem('ship')), name: 'newName'})) Commented Sep 29, 2019 at 12:44
  • I added an answer for you here: stackoverflow.com/questions/37052087/… Commented Sep 29, 2019 at 13:00

1 Answer 1

5

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"})));
Sign up to request clarification or add additional context in comments.

1 Comment

@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.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.