I\'m working on a permissions system with variable depth; depending on the complexity of a page, there could be more or less levels. I searched StackOverflow to find if this
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.
We can use the reg:
function getHowManyLevel(obj) {
let res = JSON.stringify(obj).replace(/[^{|^}]/g, '')
while (/}{/g.test(res)) {
res = res.replace(/}{/g, '')
}
return res.replace(/}/g, '').length
}
This should do it, if you wanna keep it short:
function maxDepth(object) {
if (typeof object !== "object" || object === null) {
return 0;
}
let values = Object.values(object);
return (values.length && Math.max(...values.map(value => maxDepth(value)))) + 1;
}