JavaScript: Count the object depth

Photo by Robert Bye on Unsplash

JavaScript: Count the object depth

Table of contents

No heading

No headings in the article.

let myObj = {
  name: 'hari',
  location: {
    city: 'hyderabad'
  },
  a: {
    b: {
      c: {
        d: {
          e: {
            f: {
              g: {
                h: {
                  i: 10
                }
              }
            }
          }
        }
      }
    }
  }
};

let count = 0;
function countDepth (myObj) {
  for (let object in myObj) {
    if (typeof myObj[object] === 'object') {
      countDepth(myObj[object]);
      count++;
    }
  }
  return count;
}

console.log(countDepth(myObj));
Output:
9

Execute above code here