Skip to content

Instantly share code, notes, and snippets.

@gobwas
Last active January 4, 2016 08:29
Show Gist options
  • Save gobwas/8595961 to your computer and use it in GitHub Desktop.
Save gobwas/8595961 to your computer and use it in GitHub Desktop.
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