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:
// ONLINE-RUNNER:browser;
const SEPARATOR_EXPRESSION = /[\\\/¥₩]+/i;
const toTree = (paths) => {
const map = {};
const array = [];
for (let i = 0; i < paths.length; ++i) {
const path = paths[i];
if (path) {
let mNode = map;
let aNode = array;
const parts = path.split(SEPARATOR_EXPRESSION);
for (let j = 0; j < parts.length; ++j) {
const part = parts[j];
if (part) {
let tmp = mNode[part];
if (tmp == null) { // null or undefined
const items = [];
mNode[part] = {map: {}, items: items};
aNode.push({name: part, items: items});
tmp = mNode[part];
}
mNode = tmp.map;
aNode = tmp.items;
}
}
}
}
return array;
};
// Usage example:
const paths = [
'package.json',
'src/index.js',
'src/App/index.js',
'src/App/style.css',
'public/icon.ico'
];
const tree = toTree(paths);
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.
for..of based example
Warning: this solution should be used only with iterable collections.
// ONLINE-RUNNER:browser;
const SEPARATOR_EXPRESSION = /[\\\/¥₩]+/i;
const toTree = (paths) => {
const map = {};
const array = [];
for (const path of paths) {
if (path) {
let mNode = map;
let aNode = array;
const parts = path.split(SEPARATOR_EXPRESSION);
for (const part of parts) {
if (part) {
let tmp = mNode[part];
if (tmp == null) { // null or undefined
const items = [];
mNode[part] = {map: {}, items: items};
aNode.push({name: part, items: items});
tmp = mNode[part];
}
mNode = tmp.map;
aNode = tmp.items;
}
}
}
}
return array;
};
// Usage example:
const paths = [
'package.json',
'src/index.js',
'src/App/index.js',
'src/App/style.css',
'public/icon.ico'
];
const tree = toTree(paths);
console.log(JSON.stringify(tree, null, 4));