递归解法:

方法:

  1. module.exports = function getDeep(obj) {
  2. let deep = 0
  3. const keys = Object.keys(obj)
  4. if (keys.length > 0) {
  5. deep++
  6. } else {
  7. return deep
  8. }
  9. let keyMap = {}
  10. keys.forEach(key => {
  11. if (obj[key] instanceof Object) {
  12. keyMap[key] = getDeep(obj[key])
  13. }
  14. })
  15. let maxChildLength = 0
  16. Object.keys(keyMap).forEach(key => {
  17. if (keyMap[key] > maxChildLength) {
  18. maxChildLength = keyMap[key]
  19. }
  20. })
  21. return (deep + maxChildLength)
  22. }

测试用例:

  1. // jest
  2. const getDeep = require('./getDeep')
  3. test('测试获取对象深度', () => {
  4. const obj1 = { a: { b: 1, c: { a: { m: 'n' } } } }
  5. expect(getDeep(obj1)).toBe(4)
  6. const obj2 = { a: 1 }
  7. expect(getDeep(obj2)).toBe(1)
  8. const obj3 = {}
  9. expect(getDeep(obj3)).toBe(0)
  10. const obj4 = { a: { b: 1, c: { d: 1 } }, b: { a: { c: { d: { e: 1 } } } } }
  11. expect(getDeep(obj4)).toBe(5)
  12. });