I create a tree view by transforming an array of paths into a data structure of the tree view. Here is what I want to do:
let routes = [
['top', '1.jpg'],
['top', '2.jpg'],
['top', 'unsplash', 'photo.jpg'],
['top', 'unsplash', 'photo2.jpg'],
['top', 'foo', '2.jpg'],
['top', 'foo', 'bar', '1.jpg'],
['top', 'foo', 'bar', '2.jpg']
];
into
let treeview = {
name: 'top', child: [
{name: '1.jpg', child: []},
{name: '2.jpg', child: []},
{name: 'unsplash', child: [
{name: 'photo.jpg', child: []},
{name: 'photo2.jpg', child: []}
]},
{name: 'foo', child: [
{name: '2.jpg', child: []},
{name: 'bar', child: [
{name: '1.jpg', child: []},
{name: '2.jpg', child: []}
]}
]}
]}
Now I am successfully converting a single array of elements using this method, but I cannot do this for multiple arrays. Note that the nested tree view does not contain duplicates.
function nest(arr) {
let out = [];
arr.map(it => {
if(out.length === 0) out = {name: it, child: []}
else {
out = {name: it, child: [out]}
}
});
return out;
}