JavaScript 扁平数组转树形结构:高效递归实现
可以通过递归的方式实现将扁平数组转换成树形结构。具体步骤如下:
-
首先定义一个空的树形结构对象,作为递归的起点。
-
遍历扁平数组,将每个节点按照其 'pid' 值挂载到对应的父节点下。
-
在遍历过程中,如果遇到一个节点的 'pid' 为 'null' 或者 '0',说明该节点为根节点,直接将其挂载到树形结构对象下。
-
递归处理每个节点的子节点。
-
返回树形结构对象。
下面是代码实现:
function flatToTree(flatArray) {
const tree = {};
flatArray.forEach(node => {
if (node.pid === null || node.pid === 0) { // 根节点
tree[node.id] = { ...node, children: {} };
} else { // 非根节点
const parent = tree[node.pid];
parent.children[node.id] = { ...node, children: {} };
}
});
const buildTree = (node) => {
if (Object.keys(node.children).length === 0) { // 叶子节点
delete node.children;
return node;
}
Object.values(node.children).forEach(child => {
buildTree(child);
});
return node;
}
return Object.values(tree).map(root => buildTree(root));
}
其中,'tree' 对象用于存储树形结构,其 'key' 为节点 'id','value' 为节点对象,包括自身信息和 'children' 对象。在遍历 'flatArray' 数组时,通过 'pid' 值找到对应的父节点,并将节点挂载到父节点的 'children' 对象下。
'buildTree' 函数用于递归处理每个节点的子节点,将其转换成树形结构。如果节点没有子节点,则将 'children' 属性删除。最后返回根节点数组。
原文地址: https://www.cveoy.top/t/topic/nM2x 著作权归作者所有。请勿转载和采集!