Skip to content

Instantly share code, notes, and snippets.

@aNd1coder
Forked from penguinboy/Object Flatten
Last active September 7, 2016 03:28
Show Gist options
  • Save aNd1coder/fb8ef7c76b27414c38c5a31227d9589f to your computer and use it in GitHub Desktop.
Save aNd1coder/fb8ef7c76b27414c38c5a31227d9589f to your computer and use it in GitHub Desktop.
Flatten javascript objects into a single-depth object
var flattenObject = function(ob) {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object') {
var flatObject = flattenObject(ob[i]);
toReturn[i] = ob[i];
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment