Skip to content

Instantly share code, notes, and snippets.

@robatron
Created July 29, 2013 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robatron/6107217 to your computer and use it in GitHub Desktop.
Save robatron/6107217 to your computer and use it in GitHub Desktop.

Somewhere on the page...

    /** Extend a JSON object in localStorage, as oppose to overwriting it.
    */
    var localStoreExtend = function(namespace, jsonObj){
      
        // Grab existing JSON object
        var existingObj = JSON.parse(localStorage.getItem(namespace));
        
        // Save new object fields to existing object, overwriting any fields that exist in both 
        for(var prop in JSON.parse(jsonObj)) existingObj[prop] = newObj[prop];
        
        // Save extended object back -> localStorage
        localStorage.setItem(NAMESPACE, JSON.stringify(existingObj));
    }

Then you can use the following to extend the localStorage objects:

    var NAMESPACE = 'foo';
    
    var jsonObj1 = '{"a":1,"b":2}';
    var jsonObj2 = '{"c":3,"d":4}';
    var jsonObj3 = '{"e":5,"f":6}';
    
    localStoreExtend(NAMESPACE, jsonObj1);
    localStoreExtend(NAMESPACE, jsonObj2);
    localStoreExtend(NAMESPACE, jsonObj3);

So the final result should be:

    localStorage.getItem(NAMESPACE)
    >>> '{"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment