flattening the nested object in javascript

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

提交回复
热议问题