How to count a depth level of nested JavaScript objects?


We have an array of objects, which further have nested objects like this −

const arr = [{
   id: 0, children: []
}, {
      id: 1, children: [{
      id: 2, children: []
}, {
      id: 3, children: [{
         id: 4, children: []
      }]
   }]
}];

Our job is to write a recursive function, say assignDepth() that takes in this array and assigns depth property to each nested object. Like the object with id 0 will have depth 0, id 1 will have depth 1 as well, and since id 2 and id 3 are nested inside id 1 they will have depth 1 and id 4 which is further nested inside id 3 will have depth 2.

Therefore, let’s write the code for this function. It’s a simple recursive function which iterates over sub objects repeatedly until it reaches the end of the array −

Example

const arr = [{
   id: 0, children: []
}, {
      id: 1, children: [{
      id: 2, children: []
}, {
      id: 3, children: [{
         id: 4, children: []
      }]
   }]
}];
const assignDepth = (arr, depth = 0, index = 0) => {
   if(index < arr.length){
      arr[index].depth = depth;
      if(arr[index].children.length){
         return assignDepth(arr[index].children, depth+1, 0);
      };
      return assignDepth(arr, depth, index+1);
   };
   return;
};
assignDepth(arr);
console.log(JSON.stringify(arr, undefined, 4));

Output

The output in the console will be −

[
   {
      "id": 0,
      "children": [],
      "depth": 0
   },
   {
      "id": 1,
      "children": [
         {
            "id": 2,
            "children": [],
            "depth": 1
         },
         {
            "id": 3,
            "children": [
               {
                  "id": 4,
                  "children": [],
                  "depth": 2
               }
            ],
            "depth": 1
         }
      ],
      "depth": 0
   }
]

Updated on: 25-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements