all files / src/ flattenPaths.js

100% Statements 20/20
96.97% Branches 32/33
100% Functions 6/6
100% Lines 13/13
1 statement, 1 function, 6 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                                                                         24× 22×   19× 10×   13× 12×     24×        
const isObject = value => value && typeof value === 'object'
 
/**
 * Flattens a deep structure into a flat map with dot syntax keys. So:
 *
 * {
 *   a: {
 *     b: {
 *       c: 'the',
 *       d: 'quick'
 *     },
 *     c: 'brown'
 *   },
 *   d: [
 *     'fox',
 *     'jumps',
 *     {
 *       e: 'over'
 *     }
 *   ]
 * }
 *
 * flattens to:
 *
 * {
 *   'a.b.c': 'the',
 *   'a.b.d': 'quick',
 *   'a.c': 'brown',
 *   'd[0]': 'fox',
 *   'd[1]': 'jumps',
 *   'd[2].e': 'over'
 * }
 *
 * @param object The current value we are evaluating
 * @param path The path to here
 * @param accumulator The accumulator where the values go
 */
const flattenPaths = (object, path = '', accumulator = {}) => {
  if (object) {
    if (Array.isArray(object)) {
      object.forEach((value, index) => {
        flattenPaths(value, path ? `${path}[${index}]` : String(index), accumulator)
      })
    } else if (isObject(object)) {
      Object.keys(object).forEach(key => {
        flattenPaths(object[ key ], path ? `${path}.${key}` : key, accumulator)
      })
    } else if (path) {
      accumulator[ path ] = object
    }
  }
  return accumulator
}
 
export default flattenPaths