-2

Say I have the following object:

const myObj = {
  id: 1,
  children: [
    {
      id: 2,
      children: [
        {
          id: 3
        }
      ]
    },
    {
      id: 4,
      children: [
        {
          id: 5,
          children: [
            {
              id: 6,
              children: [
                {
                  id: 7,
                }
              ]
            }
          ]
        }
      ]
    },
  ]
}

How can I tell how deep the object goes? For example the above object would be 4 levels deep.

I've searched SO and the only thing similar I could find was this question, but it did not work for me, and also seems very outdated.

TylerH
  • 20,799
  • 66
  • 75
  • 101
cup_of
  • 6,397
  • 9
  • 47
  • 94
  • 1
    Recursion where you pass `children` as root object – Justinas Feb 27 '19 at 07:23
  • _"and it did not work for me"_ - That's a really thorough explanation of the problem(s) you encountered...; _"also seems very outdated"_ - And this assumption is based on what exactly? – Andreas Feb 27 '19 at 07:28
  • The post that you reference to already have everything you need to create your own solution. – yqlim Feb 27 '19 at 07:33
  • 1
    Possible duplicate of [How to check the depth of an object?](https://stackoverflow.com/questions/13523951/how-to-check-the-depth-of-an-object) – Synoon Feb 27 '19 at 07:58

1 Answers1

3

Found an answer for this. In case anyone comes across this in the future:

const myObj={id:1,children:[{id:2,children:[{id:3}]},{id:4,children:[{id:5,children:[{id:6,children:[{id:7,}]}]}]},]}

function determineDepthOfObject(object) {
  let depth = 0;
  if (object.children) {
    object.children.forEach(x => {
      let temp = this.determineDepthOfObject(x);
      if (temp > depth) {
        depth = temp;
      }
    })
  }
  return depth + 1;
}

console.log(determineDepthOfObject(myObj))
cup_of
  • 6,397
  • 9
  • 47
  • 94