首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Typescript / JavaScript中由平面数组生成树形数组

在Typescript / JavaScript中,可以通过以下方法将平面数组转换为树形数组:

  1. 首先,我们需要定义一个递归函数,该函数将接收平面数组和父节点的ID作为参数,并返回一个树形数组。
代码语言:txt
复制
function generateTree(arr, parentId) {
  const tree = [];
  
  for (let item of arr) {
    if (item.parentId === parentId) {
      const children = generateTree(arr, item.id);
      if (children.length) {
        item.children = children;
      }
      tree.push(item);
    }
  }
  
  return tree;
}
  1. 接下来,我们可以调用这个函数来生成树形数组。
代码语言:txt
复制
const flatArray = [
  { id: 1, name: 'Node 1', parentId: null },
  { id: 2, name: 'Node 1.1', parentId: 1 },
  { id: 3, name: 'Node 1.2', parentId: 1 },
  { id: 4, name: 'Node 1.2.1', parentId: 3 },
  { id: 5, name: 'Node 2', parentId: null },
  { id: 6, name: 'Node 2.1', parentId: 5 },
];

const treeArray = generateTree(flatArray, null);
console.log(treeArray);

上述代码中,我们定义了一个名为generateTree的递归函数,它接收一个平面数组arr和父节点的IDparentId作为参数。函数首先创建一个空数组tree,用于存储生成的树形数组。

然后,我们使用for...of循环遍历平面数组arr中的每个元素。如果元素的parentId等于传入的parentId,则说明该元素是当前父节点的子节点。我们通过递归调用generateTree函数来生成子节点的子树,并将返回的子树赋值给当前元素的children属性。最后,将当前元素添加到tree数组中。

最后,我们调用generateTree函数,并传入平面数组flatArray和根节点的父节点IDnull。生成的树形数组将被打印到控制台。

这种方法可以将平面数组转换为树形数组,适用于处理具有父子关系的数据,例如组织结构、分类目录等。

腾讯云相关产品和产品介绍链接地址:

  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版(CMYSQL):https://cloud.tencent.com/product/cmysql
  • 云原生应用引擎(TKE):https://cloud.tencent.com/product/tke
  • 云存储(COS):https://cloud.tencent.com/product/cos
  • 人工智能(AI):https://cloud.tencent.com/product/ai
  • 物联网(IoT):https://cloud.tencent.com/product/iotexplorer
  • 移动开发(移动推送):https://cloud.tencent.com/product/umeng
  • 区块链(BCS):https://cloud.tencent.com/product/bcs
  • 元宇宙(Metaverse):https://cloud.tencent.com/product/metaverse
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券