Created
August 19, 2016 13:32
-
-
Save slidenerd/04b78a5732f063a6ce6d73ef66a3fb3a to your computer and use it in GitHub Desktop.
Inspired from gdibble
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
function flattenObject(ob) { | |
let toReturn = {}; | |
let flatObject; | |
for (let i in ob) { | |
console.log(i+ ' ' + typeof(ob[i])); | |
if (!ob.hasOwnProperty(i)) { | |
continue; | |
} | |
//Exclude arrays from the final result | |
//Check this http://stackoverflow.com/questions/4775722/check-if-object-is-array | |
if(ob[i] && Array === ob[i].constructor){ | |
continue; | |
} | |
if ((typeof ob[i]) === 'object') { | |
flatObject = flattenObject(ob[i]); | |
for (let x in flatObject) { | |
if (!flatObject.hasOwnProperty(x)) { | |
continue; | |
} | |
//Exclude arrays from the final result | |
if(flatObject[x] && Array === flatObject.constructor){ | |
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
Stripping out arrays means this is useless for any data containing them. Would be much better to instead flatten them too e.g.