Skip to main content

Command Palette

Search for a command to run...

JavaScript: Count the object depth

Published
•1 min read•View as Markdown
JavaScript: Count the object depth
H

Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)

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

More from this blog

E

Everyday Dev Patterns

26 posts

A collection of real-world JavaScript snippets, patterns, and gotchas from my day-to-day work.