Skip to content Skip to sidebar Skip to footer

How To Change The Value Of An Item In Localstorage Using Javascript

I have an object stored in localStorage. let ship = { name: 'black pearl', captain: 'Jack Sparraw' }; localStorage.setItem('ship', JSON.stringify(ship)); Now I want t

Solution 1:

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"})));

Post a Comment for "How To Change The Value Of An Item In Localstorage Using Javascript"