localStorage array of objects handling

后端 未结 3 745
野的像风
野的像风 2020-12-09 17:07

Array of JSON objects are stored in HTML5 localStorage.
For now delimiter is ;
For accessing and modifying array of object

相关标签:
3条回答
  • 2020-12-09 17:20

    Read variables:

    var xyz = JSON.parse( localStorage.getItem( 'element' ) );

    Store variables:

    localStorage.setItem( 'element' , JSON.stringify(xyz));

    where element is the name of the local storage variable and xyz the name of the js variable.

    0 讨论(0)
  • 2020-12-09 17:25

    Just convert the objects to JSON strings:

    localStorage.setItem("savedData", JSON.stringify(objects));
    

    And vice versa:

    objects = JSON.parse(localStorage.getItem("savedData")));
    

    Or you can add multiple objects in the same localStorage value:

    localStorage.setItem("savedData", JSON.stringify([object1, object2 /*, etc*/]));
    object1 = JSON.parse(localStorage.getItem("savedData"))[0];
    object2 = JSON.parse(localStorage.getItem("savedData"))[1];
    

    Here's the DOM storage specification.

    You can also access savedData like this:

    localStorage.savedData = "Hello world"
    var foo = localStorage.savedData;
    

    This can be used for both getting and setting the data, but it is considered less "safe" than getItem('name'); and setItem('name', 'value');

    0 讨论(0)
  • 2020-12-09 17:32

    You can use parse and stringify if the array isn't too big, but if it is, then you'll be re-encoding the whole data set for every little change.

    The library at http://rhaboo.org improves on that by giving each array entry its own localStorage entry in a linked list. That means you can make changes quite efficiently. Unlike JSON, it also honours text-named properties and three different types of sparse entry (null, undefined and simply not there.)

    BTW, I wrote rhaboo.

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