如何计算嵌套 JavaScript 对象的深度级别?

javascriptweb developmentobject oriented programming更新于 2025/10/8 15:40:17

我们有一个对象数组,其中进一步嵌套了类似这样的对象 −

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

我们的工作是编写一个递归函数,比如说,assignDepth(),它接受这个数组并为每个嵌套对象分配深度属性。例如,id 为 0 的对象深度为 0,id 1 的深度也为 1,并且由于 id 2 和 id 3 嵌套在 id 1 中,因此它们的深度为 1,而 id 4 进一步嵌套在 id 3 中,因此深度为 2。

因此,让我们为这个函数编写代码。这是一个简单的递归函数,它反复迭代子对象,直到到达数组末尾 −

示例

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));

输出

控制台中的输出将是 −

[
   {
      "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
   }
]

相关文章


有用资源