flattening the nested object in javascript

前端 未结 3 1937
花落未央
花落未央 2020-12-10 07:58

I ran into this problem, I was able to write solution which can handle array of object (not posted here) or one level deep nested object but i couldn\'t solve when the given

3条回答
  •  春和景丽
    2020-12-10 08:08

    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))

提交回复
热议问题