I'm attempting to build a string path from array-like object. But my solution is not good
// in cay thu muc
var test = [
{
name: "home",
children: [
{
name: "dev",
children: [
{
name: "ahihi.txt"
},
{
name: "hhh.js"
}
]
}
]
},
{
name: "www",
children: [
{
name: "fol1",
children: [
{
name: "fdsafd"
}
]
},
{
name: "fol3",
children: []
}
]
},
{
name: "fol2",
children: []
}
];
function printChild(items, tabNum) {
let indent = `${" ".repeat(tabNum)}`;
let child = "";
[...items].forEach(item => {
if (!item.hasOwnProperty("children")) {
child += `${indent + item.name}\n`;
} else if (item.children.length === 0) {
child += `${indent + item.name}\\\n`;
} else {
child += `${indent +
item.name +
"\\\n" +
printChild(item.children, tabNum + 1)}`;
}
});
return child;
}
function tree(test) {
let res = `\\\n${printChild(test, 1)}`;
return res;
}
console.log(tree(test));
Here's repl link: https://repl.it/repls/CrispRashHack
Ideally, this should result in something like;
home\
dev\
ahihi.txt
hhh.js
www\
fol1\
fdsafd
fol3\
fol2\