Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
* 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;
};
@slidenerd

This comment has been minimized.

Copy link

@slidenerd slidenerd commented Aug 19, 2016

Your flatten object, messes up existing values of an array if the object or any embedded object at any level has an array. HERE is an even better gist inspired from yours :)

@gdibble

This comment has been minimized.

Copy link
Owner Author

@gdibble 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