How to convert an array of arrays into a nested tree view

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:

// routes are sorted.
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;
}
+4
source share
1 answer

You can use a nested hash table to access routes and take an array as a result set. If you have only one root element, you can take the first element of the result array.

var 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']],
    result = [],
    temp = { _: result };

routes.forEach(function (path) {
    path.reduce(function (level, key) {
        if (!level[key]) {
            level[key] = { _: [] };
            level._.push({ name: key, children: level[key]._ });
        }
        return level[key];
    }, temp);
});

console.log(result);    
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result

ES6 without a temporary object, but with a named object binding with a path name.

var 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']],
    result = [];

routes.forEach(function (path) {
    path.reduce(function (level, key) {
        var temp = level.find(({ name }) => key === name);
        if (!temp) {
            temp = { name: key, children: [] };
            level.push(temp);
        }
        return temp.children;
    }, result);
});

console.log(result);    
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run codeHide result
+5
source

Source: https://habr.com/ru/post/1692781/


All Articles