Skip to content

Instantly share code, notes, and snippets.

@julienetie
Forked from slidenerd/flatten.js
Created October 9, 2016 21:12
Show Gist options
  • Save julienetie/095ff43ac2a9872bbc06b576d835bc88 to your computer and use it in GitHub Desktop.
Save julienetie/095ff43ac2a9872bbc06b576d835bc88 to your computer and use it in GitHub Desktop.
Inspired from gdibble
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