Created
November 27, 2012 15:56
Creating a nested object from nested GET parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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