-3

I have a javascript object and I would like to count the number of nested depth.

Example Object

Answer should be equal 4 (count level depth)

data: {
first: [
  {
    value: '',
    children: [
      {
       value: '',
       children: [
          {
            value: '',
            children: [
              {
                value: '',
                children: [],
              },
              {
                 value: '',
                children: [],
              },
            ],
          },
        ],
      },
    ],
  },
],

  • 2
    ... and how have you tried to achieve this so far? – Scott Sauyet Apr 24 '18 at 14:40
  • Use [recursion](https://stackoverflow.com/tags/recursion/info). – Rory O'Kane Apr 24 '18 at 14:41
  • 1
    @C.Braun: It overlaps a bit, but I don't think it's a duplicate. That asks about a generic object. This asks about a specific structure (`children`, etc.) – Scott Sauyet Apr 24 '18 at 14:41
  • Weclome to StackOverflow. Please take the [tour](https://stackoverflow.com/tour) and visit the [help center](https://stackoverflow.com/help). Please note that this is not a code-writing service. We want to help, but expect you to put in a reasonable amount of effort too. – Scott Sauyet Apr 24 '18 at 14:44

1 Answers1

0

Assuming that it is a tree (no nested objects link to ancestors) you can simply navigate the structure

function treeHeight(node) {
    return node.children.reduce(function (maxHeight, node) {
        return Math.max(maxHeight, treeHeight(node) + 1);
    }, 1);
}
B3rn475
  • 1,057
  • 5
  • 14