递归解法:
方法:
module.exports = function getDeep(obj) {
let deep = 0
const keys = Object.keys(obj)
if (keys.length > 0) {
deep++
} else {
return deep
}
let keyMap = {}
keys.forEach(key => {
if (obj[key] instanceof Object) {
keyMap[key] = getDeep(obj[key])
}
})
let maxChildLength = 0
Object.keys(keyMap).forEach(key => {
if (keyMap[key] > maxChildLength) {
maxChildLength = keyMap[key]
}
})
return (deep + maxChildLength)
}
测试用例:
// jest
const getDeep = require('./getDeep')
test('测试获取对象深度', () => {
const obj1 = { a: { b: 1, c: { a: { m: 'n' } } } }
expect(getDeep(obj1)).toBe(4)
const obj2 = { a: 1 }
expect(getDeep(obj2)).toBe(1)
const obj3 = {}
expect(getDeep(obj3)).toBe(0)
const obj4 = { a: { b: 1, c: { d: 1 } }, b: { a: { c: { d: { e: 1 } } } } }
expect(getDeep(obj4)).toBe(5)
});