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:
Here's a proposal:
function depth(o){
var values;
if (Array.isArray(o)) values = o;
else if (typeof o === "object") values = Object.keys(o).map(k=>o[k]);
return values ? Math.max.apply(0, values.map(depth))+1 : 1;
}
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'
}]
}]
}]
};
function depth(o){
var values;
if (Array.isArray(o)) values = o;
else if (typeof o === "object") values = Object.keys(o).map(k=>o[k]);
return values ? Math.max.apply(0, values.map(v=>depth(v)))+1 : 1;
}
console.log(depth(test))
EDIT: this is a generic solution. I'm still unsure whether you wanted a very specific one (i.e. with a children
field or a generic one).