FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

如何获取一个对象的深度

Open lgwebdream opened this issue 5 years ago • 2 comments

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

// 获取对象最大深度
function getObjectMaxDepth(obj) {
  let maxDepth = 0
  Object.keys(obj).forEach((key) => {
    if (typeof obj[key] === 'object') {
      let depth = getObjectMaxDepth(obj[key])
      if (depth > maxDepth) {
        maxDepth = depth
      }
    }
  })
  return maxDepth + 1
}

jiangsongyang avatar Apr 18 '22 07:04 jiangsongyang