将斜杠分隔的路径数据转换为树形结构(Next.js/React场景)
Convert Folder Upload Paths to Tree Structure
To transform your array of file paths into the desired nested tree structure, you can use an iterative approach to build the tree by traversing each path's segments and creating nodes as needed. Here's a working implementation:
Solution Code
function buildFolderTree(paths) { if (!paths.length) return null; // Initialize root node from the first path's root folder const rootSegments = paths[0].split('/'); const root = { name: rootSegments[0], children: [] }; paths.forEach(path => { const segments = path.split('/'); let currentNode = root; // Traverse intermediate folder segments (skip root and final file) for (let i = 1; i < segments.length - 1; i++) { const segment = segments[i]; // Find or create the folder node let child = currentNode.children.find(item => item.name === segment); if (!child) { child = { name: segment, children: [] }; currentNode.children.push(child); } currentNode = child; } // Add the final file as a leaf node const fileName = segments.at(-1); if (!currentNode.children.find(item => item.name === fileName)) { currentNode.children.push({ name: fileName, children: [] }); } }); return root; }
How to Use It
Pass your path array to the function, and it will return the nested tree:
const inputPaths = [ 'folder/childFile', 'folder/childFile2', 'folder/childFile3', 'folder/childFolder/childFile4', 'folder/childFolder/childFile5', 'folder/childFolder/grandchildFolder/childFile6', 'folder/childFolder/grandchildFolder/childFile7' ]; const folderTree = buildFolderTree(inputPaths); console.log(JSON.stringify(folderTree, null, 2));
Key Details
- Root Initialization: The root folder name is extracted from the first path in your array (assuming all paths share the same root).
- Segment Traversal: For each path, we split it into segments and traverse from the root, creating missing folders along the way.
- Duplicate Prevention: The code checks for existing files/folders to avoid adding duplicates.
- Case Sensitivity: By default, the function is case-sensitive. To make it case-insensitive, modify the
findchecks to usetoLowerCase()on both the segment and node name.
Output
The code will produce exactly the tree structure you specified:
{ "name": "folder", "children": [ { "name": "childFile", "children": [] }, { "name": "childFile2", "children": [] }, { "name": "childFile3", "children": [] }, { "name": "childFolder", "children": [ { "name": "childFile4", "children": [] }, { "name": "childFile5", "children": [] }, { "name": "grandchildFolder", "children": [ { "name": "childFile6", "children": [] }, { "name": "childFile7", "children": [] } ] } ] } ] }
内容的提问来源于stack exchange,提问作者Tarun
相关产品推荐
相关产品推荐

