在Typescript / JavaScript中,可以通过以下方法将平面数组转换为树形数组:
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;
}
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
。生成的树形数组将被打印到控制台。
这种方法可以将平面数组转换为树形数组,适用于处理具有父子关系的数据,例如组织结构、分类目录等。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云