People! It's my first question here as junior frontend dev.
I have function (https://jsfiddle.net/kmjhsbt9/) which transforms a flat array like this :
const filePaths = [
'src/lib/git.js',
'src/lib/server.js',
'build/css/app.css',
'externs/test/jquery.js',
];
into object tree like this:
[
src: {
lib: {
git.js: 'file',
server.js: 'file',
}
},
build: {
css: {
app.css: 'file'
}
}
.....
]
Please, help me to understand how I can rewrite the function so that it outputs the result in this format:
[
{
text: src,
children: [
{
text: 'lib',
children: [
{
text: git.js,
children: [
{
text: 'file'
},
]
},
{
text: server.js,
children: [
{
text: 'file'
},
]
}
]
}
]
},
{
text: build,
children: [
{
text: app.css,
children: [
text: app.css,
children: [
{
text: 'file'
}
]
]
}
]
}
.....
]
function:
const getTree = (arr) => {
let fileTree = [];
function mergePathsIntoFileTree(prevDir, currDir, i, filePath) {
if (!prevDir.hasOwnProperty(currDir)) {
prevDir[currDir] = {};
}
if (i === filePath.length - 1) {
prevDir[currDir] = 'file';
}
return prevDir[currDir];
}
function parseFilePath(filePath) {
let fileLocation = filePath.split('/');
if (fileLocation.length === 1) {
return (fileTree[fileLocation[0]] = 'file');
}
fileLocation.reduce(mergePathsIntoFileTree, fileTree);
}
arr.forEach(parseFilePath);
return fileTree;
}
Thank you very much, in advance!