flattening the nested object in javascript

前端 未结 3 1934
花落未央
花落未央 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:01

    I am very late to the party but it can be easily achieved with a module like Flatify-obj.

    Usage:

       const flattenObject = require('flatify-obj');
    
       flattenObject({foo: {bar: {unicorn: '                                                                    
    0 讨论(0)
  • 2020-12-10 08:02

    one more simple example with Object.keys

     const apple = { foo: { boo : { doo : 1 } } }
    
    
    let newObj = {}
    const format = (obj,str) => {
      Object.keys(obj).forEach((item)=>{
         if(typeof obj[item] ==='object'){
            const s = !!str? str+'.'+item:item
            format(obj[item],s)
         } else {
           const m = !!str?`${str}.`:''
           newObj[m+item]= obj[item]
         }
      })
    
    }
    
    format(apple,'')
    
    console.log(newObj)

    0 讨论(0)
  • 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))

    0 讨论(0)
提交回复
热议问题