Updating/editing localStorage - JSONObject

后端 未结 2 1128
有刺的猬
有刺的猬 2021-01-25 11:00

Is it possible to edit a JSON object stored on web local storage? Currently I have a stringified JSON object

{fname\":\"Jerry\",\"lname\":\"Lewis\",\"email\":\"Jl

相关标签:
2条回答
  • 2021-01-25 11:30

    You can do:

    var myObj = JSON.parse(localStorage.getItem("yourKey"));
    myObj.fname = "Clyde"; //change fname to Clyde
    localStorage.setItem("yourKey", JSON.stringify(myObj));
    
    0 讨论(0)
  • 2021-01-25 11:37

    It's very inefficient to parse and stringify large objects for small reasons. That's why I wrote http://rhaboo.org. It uses lots of localStorage entries so you can change bits at a time efficiently.

    You'd write:

    var store = new Rhaboo.persistent("My Store Name");
    if (store.friends === undefined) store.write('friends', [
      {fname":"Jerry", "lname":"Lewis", "email":"Jlewis@hollywood.com"},
      {fname":"Effie", "lname":"Bevan", "email":"ebevan@wales.com"}
    ]);
    store.friends[0].write('phone', '0123 456789');
    console.log(store.friends[0].phone);
    

    Now when you add the phone number, it only rewrites two localStorage entries, namely, the new one for the phone number itself, and the previously final property of Jerry which was his email. That's because it hangs the entries for the properties in a linked list. Effie's entry and the friend array itself are untouched, as is everything in Lewis up to the email. That's quite a lot more efficient, especially on large data sets.

    0 讨论(0)
提交回复
热议问题