1

I found many solutions to find depth of nodes in a nested json file. but it throws me an error "maximum recursion depth exceeded " when it set maximum recursion limit, it says "process exceeded with some error code" As a part of my problem, I also need to find out key names of each node in the json file.

example json :

"attachments": {
            "data": [
               {
                  "media": {
                     "image": {
                        "height": 400,
                        "src": "https://scontent.xx.fbcdn.net/v/t1.0-1/10250217_10152130974757825_8645405213175562082_n.jpg?oh=904c1785fc974a3208f1d18ac07d59f3&oe=57CED94D",
                        "width": 400
                     }
                  },
                  "target": {
                     "id": "74286767824",
                     "url": "https://www.facebook.com/LAInternationalAirport/"
                  },
                  "title": "Los Angeles International Airport (LAX)",
                  "type": "map",
                  "url": "https://www.facebook.com/LAInternationalAirport/"
               }
            ]
         }

the output should be:

nodes: [data [media [image[height,width,src]], target[id,url], title, type, url]]

depth: 4

3 Answers 3

1

If anyone else came here and found that the accepted answer does not work because Object.keys() for a string returns an array of each character of string and thus for either large objects or objects with large strings it just fails. Here is something that works ->

function getDepth(obj){
    if(!obj || obj.length===0 || typeof(obj)!=="object") return 0;
    const keys = Object.keys(obj);
    let depth = 0;
    keys.forEach(key=>{
        let tmpDepth = getDepth(obj[key]);
        if(tmpDepth>depth){
            depth = tmpDepth;
        }
    })
    return depth+1;
}

Exmaple - https://jsfiddle.net/95g3ebp7/

Sign up to request clarification or add additional context in comments.

Comments

1

Try the following function:


 const getDepth = (
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  obj: Record<string, any>,
  tempDepth?: number
): number => {
  let depth = tempDepth ? tempDepth : 0;
  if (obj !== null) {
    depth++;
    if (typeof obj === 'object' && !Array.isArray(obj)) {
      const keys = Object.keys(obj);
      if (keys.length > 0)
        depth = Math.max(
          ...keys.map((key) => {
            return getDepth(obj[key], depth);
          })
        );
    } else if (Array.isArray(obj)) {
      if (obj.length > 0)
        depth = Math.max(
          ...obj.map((item) => {
            return getDepth(item, depth);
          })
        );
    }
  }
  return depth;
};

If you try this, I believe you have to get 7.


  console.log(getDepth({
    a: {
      b: { a: [{ a: { a: [] } }] }
    }
  }));

Comments

0
function geth(obj) {
  var depth = 0;
  var k = Object.keys(obj);
  console.log(k);
  for (var i in k) {
      var tmpDepth = geth(obj[k[i]]);
      if (tmpDepth > depth) {
          depth = tmpDepth
      }
  }
  return 1 + depth;
}

3 Comments

this will recursively calculate the depth of json tree
As it uses recursion, it fails for my object which was very large and nested. Can there be an iterative approach for this ? It will of great help.
This won't work if the object contains even a single string value. It will result in infinite recursion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.