Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 ) );
};
@ghost

This comment has been minimized.

Copy link

ghost commented Jun 11, 2017

doesnt work with cyclic objects like window

@hendrikras

This comment has been minimized.

Copy link

hendrikras commented Mar 13, 2018

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

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

This comment has been minimized.

Copy link

tatarqa commented Jun 4, 2018

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
You can’t perform that action at this time.