Skip to content

Instantly share code, notes, and snippets.

@dominikwilkowski
Created February 22, 2017 23:11
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dominikwilkowski/ac65056fbb102b8003d6b33270a9d660 to your computer and use it in GitHub Desktop.
Save dominikwilkowski/ac65056fbb102b8003d6b33270a9d660 to your computer and use it in GitHub Desktop.
Flatten javascript objects into a single-depth object with ES6

Flatten a deep javascript object into single-depth object with ES6

Call it via:

const flat = flatten( realDeepObject );

Test case:

const realDeepObject = {
  level1: {
    level2: {
      level3: {
        more: 'stuff', //duplicate key
        other: 'stuff',
        level4: {
          the: 'end',
        },
      },
    },
    level2still: {
      last: 'one',
    },
    am: 'bored',
  },
  more: 'stuff', //duplicate key
  ipsum: {
    lorem: 'latin',
  },
};

const flat = flatten( realDeepObject );

console.log( flat );

Output:

{ '/level1/level2/level3/more': 'stuff',
  '/level1/level2/level3/other': 'stuff',
  '/level1/level2/level3/level4/the': 'end',
  '/level1/level2still/last': 'one',
  '/level1/am': 'bored',
  '/more': 'stuff',
  '/ipsum/lorem': 'latin' }

(You can replace the separators / with a dot . to make it fit your job)

/**
* PRIVATE
* Flatten a deep object into a one level object with it’s path as key
*
* @param {object} object - The object to be flattened
*
* @return {object} - The resulting flat object
*/
const flatten = object => {
return Object.assign( {}, ...function _flatten( objectBit, path = '' ) { //spread the result into our return object
return [].concat( //concat everything into one level
...Object.keys( objectBit ).map( //iterate over object
key => typeof objectBit[ key ] === 'object' ? //check if there is a nested object
_flatten( objectBit[ key ], `${ path }/${ key }` ) : //call itself if there is
( { [ `${ path }/${ key }` ]: objectBit[ key ] } ) //append object with it’s path as key
)
)
}( object ) );
};
Copy link

ghost commented Jun 11, 2017

doesnt work with cyclic objects like window

@hendrikras
Copy link

runtime error if the value of a (nested) object is null, fixed it by adding:

if (objectBit) { // line 11
return [] // line 18

@oujezdsky
Copy link

omg js sucks so hard, thanks anyway

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment