Last active
January 4, 2016 08:29
-
-
Save gobwas/8595961 to your computer and use it in GitHub Desktop.
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
function unflatten(path, obj, value) { | |
var key, child, result; | |
if (Object.prototype.toString.call(path) == '[object Object]') { | |
result = {}; | |
for (key in path) { | |
if (path.hasOwnProperty(key)) { | |
unflatten(key.split('.'), result, path[key]); | |
} | |
} | |
return result; | |
} | |
key = path.shift(); | |
if (path.length == 0) { | |
obj[key] = value; | |
return obj; | |
} | |
if ((child = obj[key]) == void 0) { | |
child = obj[key] = {}; | |
} | |
unflatten(path, child, value); | |
return obj; | |
} | |
function flatten(obj) { | |
var result = {}, value, nestedValue, nested; | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
value = obj[key]; | |
if (Object.prototype.toString.call(value) == '[object Object]') { | |
nested = flatten(value); | |
for (var nestedKey in nested) { | |
if (nested.hasOwnProperty(nestedKey)) { | |
nestedValue = nested[nestedKey]; | |
result[key + "." + nestedKey] = nestedValue; | |
} | |
} | |
} else { | |
result[key] = value; | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment