I am looking for a quick and efficient way to determine the maximum "depth" of a JSON object. For instance, an object like
{
a: "aVal",
b: {
b1: "b1Val",
b2: "b2Val",
b3: {
b3a: "b3aVal"
}
}
}
would have a maximum depth of 2, since there are two nested objects at "b" and "b3".
Is there a lodash solution for this? or a quick javascript function? All I can think of is iterating through using Object.keys() and checking every nested object to determine which is the deepest, but there must be a more optimal solution than that.
Any ideas?
>Solution :
You can use recursion:
const data = {a:"aVal",b:{b1:"b1Val",b2:"b2Val",b3:{b3a:"b3aVal"}}};
function maxDepth(o, depth = 0) {
return Math.max(
depth,
...Object.values(o)
.filter(v => typeof v === "object")
.map(v => maxDepth(v, depth + 1))
);
}
console.log(maxDepth(data));
Note: this won’t work if the Object contains Array or
nullvalues (they are Objects too). More checks would need to be added. I kept it simple as per your sample data