首页 > 解决方案 > Javascript如何获取数组深度

问题描述

像这样的数组:

const array = [
  {
    title: 'xx',
    children: [
      {
        title: 'xxx',
        children: [
           { title: 'xxx' }
        ]
      }        
    ]
  }
]

深度是 3,我如何使用函数获得深度,或者让数组变成这个

const array = [
  {
    title: 'xx',
    depth: 1,
    children: [
      {
        title: 'xxx',
        depth: 2,
        children: [
           { title: 'xxx', depth: 3 }
        ]
      }        
    ]
  }
]

javascript有更好的方法吗?

标签: javascriptalgorithm

解决方案


您可以使用一个简单的递归函数来装饰每个级别的孩子。

const array = [
  {
    title: 'Title 1',
    children: [
      {
        title: 'Title 2',
        children: [
           { 
             title: 'Title 3' 
           }
        ]
      }        
    ]
  }
];

const depthArray = depthDecorator(array);
console.log(depthArray);

function depthDecorator(array, depth = 1) {
  return array.map((child) => Object.assign(child, { 
    depth, 
    children: depthDecorator(child.children || [], depth + 1)
  }));
}


推荐阅读