如何用JavaScript将大量路径数组转换为父子层级JSON对象
JS路径数组转嵌套树形结构高效实现方案
核心思路
要实现数万条路径的高效转换,核心是用哈希表存储已创建节点的引用,避免每次查找子节点时遍历整个树,整体时间复杂度为线性O(n)(n为所有路径的片段总数),性能足够支撑十万级数据量。
实现代码
function pathsToTree(paths) { const result = []; // 哈希表存储[完整路径: 对应节点对象]的映射,实现O(1)查找节点 const nodeMap = {}; for (const fullPath of paths) { // 按反斜杠拆分路径为片段数组 const segments = fullPath.split('\\'); let currentPath = ''; // 当前层级节点的父容器,初始为根结果数组 let parentList = result; for (let i = 0; i < segments.length; i++) { const currentSeg = segments[i]; // 拼接当前层级的完整路径作为哈希表key,避免重名节点冲突 currentPath = currentPath ? `${currentPath}\\${currentSeg}` : currentSeg; // 节点不存在则创建并加入父容器 if (!nodeMap[currentPath]) { const newNode = { data: currentSeg }; // 非叶子节点提前初始化children数组 if (i < segments.length - 1) { newNode.children = []; } nodeMap[currentPath] = newNode; parentList.push(newNode); } // 更新父容器为当前节点的children,处理下一层级 parentList = nodeMap[currentPath].children || []; } } return result; } // 测试示例 const inputArray = [ "Company_stock_content\\LightRhythmVisuals\\LRV_HD", "Big Media Test\\ArtificiallyAwake\\AA_HD", "Big Media Test\\Company\\TestCards_3840x2160\\TestCards_1920x1080" ]; const treeResult = pathsToTree(inputArray); // 输出JSON格式结果 console.log(JSON.stringify(treeResult, null, 2));
优化说明
- 如果存在大量超长路径,可将
nodeMap替换为ES6的Map类型,字符串key的查找性能会略优于普通对象 - 代码天然支持重复路径去重,相同路径不会重复创建节点
- 若需要叶子节点也保留空
children数组,只需去掉if (i < segments.length - 1)判断,统一给所有节点加children: []即可
内容的提问来源于stack exchange,提问作者Carpathea
相关产品推荐
相关产品推荐

