Skip to content

Instantly share code, notes, and snippets.

@bastien
Created November 27, 2012 15:56
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 bastien/4155027 to your computer and use it in GitHub Desktop.
Save bastien/4155027 to your computer and use it in GitHub Desktop.
Creating a nested object from nested GET parameters
var obj = {};
var param1 = "monkey[foo][bar][test1]";
var param2 = "monkey[foo][foo][test2]";
var keys1 = param1.replace(/\]/g, '').split('[');
var keys2 = param2.replace(/\]/g, '').split('[');
var deserialize = function(obj, keys, value){
var pointer = obj;
var index = 0;
keys.forEach(function(key){ // do not use forEach, not working with IE !!!!
if((index + 1) == keys.length){
pointer[key] = value
}else if(pointer[key] === undefined){
pointer[key] = {};
}
index++;
pointer = pointer[key];
});
}
deserialize(obj, keys1, '1');
deserialize(obj, keys2, '2');
var obj2 = { monkey: { foo: { bar: "1", foo: "2" } }};
if ( JSON.stringify(obj)==JSON.stringify(obj2) ){
console.log("works!");
}else {
console.log("failed");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment