Save Javascript objects in sessionStorage

后端 未结 9 640
抹茶落季
抹茶落季 2020-12-02 05:14

SessionStorage and LocalStorage allows to save key/value pairs in a web browser. The value must be a string, and save js objects is not trivial.

var user = {         


        
相关标签:
9条回答
  • 2020-12-02 05:40

    This is a dynamic solution which works with all value types including objects :

    class Session extends Map {
      set(id, value) {
        if (typeof value === 'object') value = JSON.stringify(value);
        sessionStorage.setItem(id, value);
      }
    
      get(id) {
        const value = sessionStorage.getItem(id);
        try {
          return JSON.parse(value);
        } catch (e) {
          return value;
        }
      }
    }
    

    Then :

    const session = new Session();
    
    session.set('name', {first: 'Ahmed', last : 'Toumi'});
    session.get('name');
    
    0 讨论(0)
  • 2020-12-02 05:42

    Could you not 'stringify' your object...then use sessionStorage.setItem() to store that string representation of your object...then when you need it sessionStorage.getItem() and then use $.parseJSON() to get it back out?

    Working example http://jsfiddle.net/pKXMa/

    0 讨论(0)
  • 2020-12-02 05:43

    You can create 2 wrapper methods for saving and retrieving object from session storage.

    function saveSession(obj) {
      sessionStorage.setItem("myObj", JSON.stringify(obj));
      return true;
    }
    
    function getSession() {
      var obj = {};
      if (typeof sessionStorage.myObj !== "undefined") {
        obj = JSON.parse(sessionStorage.myObj);
      }
      return obj;
    }
    

    Use it like this:- Get object, modify some data, and save back.

    var obj = getSession();
    
    obj.newProperty = "Prod"
    
    saveSession(obj);
    
    0 讨论(0)
提交回复
热议问题