Skip to content

Instantly share code, notes, and snippets.

@klederson
Created October 8, 2012 18:23
Show Gist options
  • Save klederson/3854049 to your computer and use it in GitHub Desktop.
Save klederson/3854049 to your computer and use it in GitHub Desktop.
Adding Multidimensional Support for javascript / html5 sessionStorage , localStorage or just Storage object
/**
*
* MOVED TO: https://github.com/iFind/html5MultidimensionalStorage
*
* This methods extends the default HTML5 Storage object and add support
* to set and get multidimensional data
*
* @example Storage.setObj('users.albums.sexPistols',"blah");
* @example Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
* @example Storage.setObj('users.albums.sexPistols.sid',"Other songs");
*
* @example Storage.getObj('users');
* @example Storage.getObj('users.albums');
* @example Storage.getObj('users.albums.sexPistols');
* @example Storage.getObj('users.albums.sexPistols.sid');
* @example Storage.getObj('users.albums.sexPistols.nancy');
*
* This is just a prototype and is not recommended to use at production apps
* USE AT YOUR OWN RISK
*
* @author Klederson Bueno <klederson@klederson.com>
*/
//Add Storage support for objects
Storage.prototype.__walker = function(path,o) {
//Validate if path is an object otherwise returns false
if(typeof path !== "object")
return false;
if(path.length == 0)
return o;
for(i in path){
var prop = path[i];
//Check if path step exists
if(o.hasOwnProperty(prop)){
var val = o[prop];
if(typeof val == 'object'){
path.splice(0,1);
return this.__walker(path,val);
} else {
return val;
}
}
}
}
Storage.prototype.setObj = function(key, value) {
var path = key.split('.');
//First level is always the localStorage key pair item
var _key = path[0];
var os = JSON.parse(this.getItem(_key)); //general storage key pair element
path.splice(0,1);
if(os == null) {
os = {};
this.setItem(_key,JSON.stringify(os));
}
var innerWalker = function(path,o) {
//Validate if path is an object otherwise returns false
if(typeof path !== "object")
return false;
if(path.length == 1) {
o[path[0]] = value;
return o;
}
var val = null;
for(i in path){
var prop = path[i];
//Check if path step exists
if(o.hasOwnProperty(prop)) {
val = o[prop];
if(typeof val == 'object'){
path.splice(0,1);
return innerWalker(path,val);
}
} else {
//create depth
o[prop] = {};
val = o[prop];
path.splice(0,1);
return innerWalker(path,val);
}
}
}
innerWalker(path,os);
this.setItem(_key,JSON.stringify(os));
}
Storage.prototype.getObj = function(key) {
key = key.split('.');
//First level is always the localStorage key pair item
var _key = key[0];
var o = JSON.parse(this.getItem(_key));
if(o == null)
return false;
key.splice(0,1);
return this.__walker(key,o);
}
@Midor1
Copy link

Midor1 commented Jul 27, 2018

This is exactly what I'm looking for, much obliged!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment