How to determine the maximum depth of nested objects in JSON?

Viewed 26

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?

1 Answers

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 null values (they are Objects too). More checks would need to be added. I kept it simple as per your sample data

Related