EN
JavaScript - convert file paths to tree (multi-level arrays)
4 points
In this short article, we would like to show how to convert file paths to tree in JavaScript.
Conversion concept:

Practical example:
xxxxxxxxxx
1
const SEPARATOR_EXPRESSION = /[\\\/¥₩]+/i;
2
3
const toTree = (paths) => {
4
const map = {};
5
const array = [];
6
for (let i = 0; i < paths.length; ++i) {
7
const path = paths[i];
8
if (path) {
9
let mNode = map;
10
let aNode = array;
11
const parts = path.split(SEPARATOR_EXPRESSION);
12
for (let j = 0; j < parts.length; ++j) {
13
const part = parts[j];
14
if (part) {
15
let tmp = mNode[part];
16
if (tmp == null) { // null or undefined
17
const items = [];
18
mNode[part] = {map: {}, items: items};
19
aNode.push({name: part, items: items});
20
tmp = mNode[part];
21
}
22
mNode = tmp.map;
23
aNode = tmp.items;
24
}
25
}
26
}
27
}
28
return array;
29
};
30
31
32
// Usage example:
33
34
const paths = [
35
'package.json',
36
'src/index.js',
37
'src/App/index.js',
38
'src/App/style.css',
39
'public/icon.ico'
40
];
41
42
const tree = toTree(paths);
43
44
console.log(JSON.stringify(tree, null, 4));
Notes:
¥
and₩
were used because of possible Japanese and Korean path separators,- in practise web browsers' APIs work on slashes only, so it is not needed to use
¥
and₩
separators.
Warning: this solution should be used only with iterable collections.
xxxxxxxxxx
1
const SEPARATOR_EXPRESSION = /[\\\/¥₩]+/i;
2
3
const toTree = (paths) => {
4
const map = {};
5
const array = [];
6
for (const path of paths) {
7
if (path) {
8
let mNode = map;
9
let aNode = array;
10
const parts = path.split(SEPARATOR_EXPRESSION);
11
for (const part of parts) {
12
if (part) {
13
let tmp = mNode[part];
14
if (tmp == null) { // null or undefined
15
const items = [];
16
mNode[part] = {map: {}, items: items};
17
aNode.push({name: part, items: items});
18
tmp = mNode[part];
19
}
20
mNode = tmp.map;
21
aNode = tmp.items;
22
}
23
}
24
}
25
}
26
return array;
27
};
28
29
30
// Usage example:
31
32
const paths = [
33
'package.json',
34
'src/index.js',
35
'src/App/index.js',
36
'src/App/style.css',
37
'public/icon.ico'
38
];
39
40
const tree = toTree(paths);
41
42
console.log(JSON.stringify(tree, null, 4));