flattening the nested object in javascript

You should be able to do it fairly simply with recursion. The way it works, is you just recursively call a parser on object children that prepend the correct key along the way down. For example (not tested very hard though):

const source = {
  a: 1,
  b: {
    c: true,
    d: {
      e: 'foo'
    }
  },
  f: false,
  g: ['red', 'green', 'blue'],
  h: [{
    i: 2,
    j: 3
  }]
}

const flatten = (obj, prefix = '', res = {}) => 
  Object.entries(obj).reduce((r, [key, val]) => {
    const k = `${prefix}${key}`
    if(typeof val === 'object'){ 
      flatten(val, `${k}.`, r)
    } else {
      res[k] = val
    }
    return r
  }, res)
 
console.log(flatten(source))

Leave a Comment