面试笔试题:扁平化对象成特定结构

77 阅读1分钟

面试题 扁平化对象成特定结构

const obj = {
  a:{
    b:'hello',
    c:{
      d:'world',
      f:{
        g:'hahaha'
      }
    }
  },
  e:'hello world',
  h:{
    i:'yeyeyeye'
  }
}

转成类似
{
    a.b:'hello',
    a.c.d:'world',
    ...
    e:'hello world',
    h.i:'yeyeyeye'
}

function transTree(obj,unionkey='',targetObj={}){
  if(Object.keys(obj).length===1&&typeof obj[Object.keys(obj)[0]] === 'string'){
    unionkey=unionkey+'.'+Object.keys(obj)[0]
   return targetObj[unionkey] = Object.values(obj)[0]
  }
  Object.keys(obj).forEach(key=>{
    const targetKey = unionkey?unionkey+'.'+key:key
    if(typeof obj[key] === 'string'){
      targetObj[targetKey] = obj[key]
    }else{
      transTree(obj[key],targetKey,targetObj)
    }
  })
  return targetObj
}

console.log(transTree(obj))

感觉有优化空间,欢迎指正.