How do I update localStorage items?

前端 未结 5 2038
悲哀的现实
悲哀的现实 2021-01-18 17:55

I\'m having a problem where the cached object doesn\'t resemble the correct data so I figured it I can push up the most uptodate version to the browser cache it will solve m

5条回答
  •  广开言路
    2021-01-18 18:42

    A response specifically for the asker of this duplicate question:

    LocalStorage can only store strings, which is why you're stringifying your object before storing it. To manipulate the stored string as an object, you can pass it to JSON.parse (assuming it's properly JSON-formatted). Then to store the modified version, you need to convert it back into a string.

    // Creates JSON-formatted object, converts it to a string and stores the string as "ship"
    const ship = { name: "black pearl", captain: "Jack Sparrow" };
    const originalStringifiedForStorgage = JSON.stringify(ship);
    localStorage.setItem("ship", JSON.stringify(ship));
    
    // Retrieves the string and converts it to a JavaScript object 
    const retrievedString = localStorage.getItem("ship");
    const parsedObject = JSON.parse(retrievedString);
    
    // Modifies the object, converts it to a string and replaces the existing `ship` in LocalStorage
    parsedObject.name = "newName";
    const modifiedndstrigifiedForStorage = JSON.stringify(parsedObject);
    localStorage.setItem("ship", strigifiedForStorage);
    

提交回复
热议问题