Skip to content

Instantly share code, notes, and snippets.

@slidenerd
Created August 19, 2016 13:32
Show Gist options
  • Save slidenerd/04b78a5732f063a6ce6d73ef66a3fb3a to your computer and use it in GitHub Desktop.
Save slidenerd/04b78a5732f063a6ce6d73ef66a3fb3a to your computer and use it in GitHub Desktop.

Revisions

  1. slidenerd created this gist Aug 19, 2016.
    31 changes: 31 additions & 0 deletions flatten.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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;
    }