此贴终结,最终代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const result = [
['1600639146', '文件夹1'],
[ '1600639146', '文件夹1', '新建文件夹' ],
[ '1600639146', '文件夹1', '新建文件夹', '文件夹' ],
[ '1600639146', '文件夹3' ],
['1600639146', '文件夹2', '新文件夹', '文件夹', 'folder'],
['1600639146', '文件夹2'],
['1600639146', '文件夹2', '新文件夹'],
['1600639146', '文件夹2', '新文件夹', '文件夹']
]
function solve(arr) {
let rootStr = null
arr.forEach(folderPath => {
rootStr = folderPath.shift()
})
arr = arr.sort((x, y) => {
return x.length - y.length
})
const rootNode = { label: rootStr }
arr.forEach(folderPath => {
onTree(rootNode, folderPath)
})
console.log('rootNode', rootNode)
}
function onTree(node, path) {
const root = node
for (let i = 0; i < path.length - 1; i++) {
node = node.children.find(item => item.label === path[i])
}
if (node.children) {
node.children.push({
label: path[path.length - 1]
})
} else {
node.children = [{
label: path[path.length - 1]
}]
}
}
solve(result)
</script>
</body>
</html>