-
-
Save gdibble/9e0f34f0bb8a9cf2be43 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
/* | |
* 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :)