let str={a:{ b: { c:1}} 变为{a.b.c:1}(急,求解)

let str=

 {
  a:
   {
     b:
       {
         c:1
       }
   },
f:
   {
     g:
       {
         h:1
       }
   }
 }

变为{a.b.c:1,f.g.h:1}

阅读 1.5k
2 个回答

刚看到你才问了扁平转立体的,兄弟可以先自己想一想嘛。

我简单手撸了一个,稍微测了一下应该没问题:

function transform(obj) {
  const result = {}
  const loop = [{ parentKey: '', item: obj }]

  while (loop.length) {
    const { parentKey, item } = loop.pop()

    Object.keys(item).forEach(key => {
      const value = item[key]
      const nextKey = parentKey ? `${parentKey}.${key}` : key

      if (Object.prototype.toString.call(item[key]) === '[object Object]') {
        loop.push({ parentKey: nextKey, item: value })
      } else {
        result[nextKey] = value
      }
    })
  }

  return result
}

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏