How to check the depth of an object?
Well, here you go buddy, a function that does exactly what you need!
utils.depthOf = function(object) {
var level = 1;
for(var key in object) {
if (!object.hasOwnProperty(key)) continue;
if(typeof object[key] == 'object'){
var depth = utils.depthOf(object[key]) + 1;
level = Math.max(depth, level);
}
}
return level;
}
A lot easier than we thought it would be. The issue was how it was incremented, it shouldn't have been recursively adding, rather getting the bottom-most and adding one, then choosing the max between two siblings.
Back from the dead! Throwing my solution into the mix -
function depth (t, mem = new Set)
{ if (mem.has(t))
return Infinity
else switch (mem.add(t), t?.constructor)
{ case Object:
case Array:
return 1 + Math.max
( -1
, ...Object
.values(t)
.map(_ => depth(_, mem))
)
default:
return 0
}
}
console.log(depth({a: {b: {c: "z"}}})) // 3
console.log(depth({a: "z"})) // 1
console.log(depth({})) // 0
console.log(depth("z")) // 0
console.log(depth({a: [{b: "z"}]})) // 3
const a = []
a[0] = a
console.log(depth(a)) // Infinity
This old question was recently resurrected and I don't see any answers as simple as this one (to be fair, this uses techniques not available when the question was written):
const objectDepth = (o) =>
Object (o) === o ? 1 + Math .max (-1, ... Object .values(o) .map (objectDepth)) : 0
console .log (objectDepth ({foo: {bar: {baz: 'baa'}}}))
console .log (objectDepth ({abc: 'xyz'}))
This, like most answers here, will fail when the input object is cyclic. An answer that addresses that limitation would require much more sophistication.