Skip to content

Instantly share code, notes, and snippets.

@gdibble
Forked from penguinboy/Object Flatten
Last active June 12, 2021 00:28
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save gdibble/9e0f34f0bb8a9cf2be43 to your computer and use it in GitHub Desktop.
Save gdibble/9e0f34f0bb8a9cf2be43 to your computer and use it in GitHub Desktop.
/*
* Flatten Object @gdibble: Inspired by https://gist.github.com/penguinboy/762197
* input: { 'a':{ 'b':{ 'b2':2 }, 'c':{ 'c2':2, 'c3':3 } } }
* output: { 'a.b.b2':2, 'a.c.c2':2, 'a.c.c3':3 }
*/
var flattenObject = function(ob) {
var toReturn = {};
var flatObject;
for (var i in ob) {
if (!ob.hasOwnProperty(i)) {
continue;
}
if ((typeof ob[i]) === 'object') {
flatObject = flattenObject(ob[i]);
for (var x in flatObject) {
if (!flatObject.hasOwnProperty(x)) {
continue;
}
toReturn[i + (!!isNaN(x) ? '.' + x : '')] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
};
@gdibble
Copy link
Author

gdibble commented May 12, 2017

Awesome, thanks for advacing the code @slidenerd 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment