I\'m trying to write a function that will loop through my object and return the level depth of the object.
For example, if I ran the function on this object:
You could map the depth of every children and take the maximum value of it.
function getDepth(object) {
return 1 + Math.max(0, ...(object.children || []).map(getDepth));
}
var test = { name: 'item 1', children: [{ name: 'level 1 item', children: [{ name: 'level 2 item' }, { name: 'second level 2 item', children: [{ name: 'level 3 item' }] }] }] },
depth = getDepth(test) - 1; // zero based
console.log(depth);