Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading