EN
JavaScript - convert file paths to tree (multi-level maps)
12
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 tree = {};
for (let i = 0; i < paths.length; ++i) {
const path = paths[i];
if (path) {
let node = tree;
const parts = path.split(SEPARATOR_EXPRESSION);
for (let j = 0; j < parts.length; ++j) {
const part = parts[j];
if (part) {
node = node[part] ?? (node[part] = {});
}
}
}
}
return tree;
};
// 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 tree = {};
for (const path of paths) {
if (path) {
let node = tree;
const parts = path.split(SEPARATOR_EXPRESSION);
for (const part of parts) {
if (part) {
node = node[part] ?? (node[part] = {});
}
}
}
}
return tree;
};
// 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));