javascript - 如何将数组数组转换为深层嵌套 TreeView

标签 javascript algorithm tree grouping

我正在通过将路径数组转换为 TreeView 数据结构来构建 TreeView 。这是我想要做的:

// 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: []}
        ]}
    ]}
]}

现在我已经通过这种方法成功地转换了单个项目数组,但无法对多个项目进行转换。另请注意,嵌套 TreeView 不包含重复项。

function nest(arr) {
    let out = [];
    arr.map(it => {
        if(out.length === 0) out = {name: it, child: []}
        else {
            out = {name: it, child: [out]}
        }
    });
    return out;
}

最佳答案

您可以使用嵌套哈希表来访问路由,并将数组作为结果集。如果只有一个根元素,则可以取结果数组的第一个元素。

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; }

ES6 没有临时对象,但使用路径名搜索命名对象。

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; }

关于javascript - 如何将数组数组转换为深层嵌套 TreeView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48467764/

相关文章:

javascript - 如何通过 AJAX( native JS)调用 ASP.NET WebMethod

javascript - Mapbox:获取坐标国家/地区

javascript - 无法在 dropzone 中添加事件处理程序

java - 2-3 树 - split 困难

java - 无法获取 k-ary 树的叶子数

javascript - jquery 屏蔽输入只有第一个数字可选其余强制

c++ - C++ 动态编程中的 UVa 3n + 1

c - 平方根为整数的数字,没有数学库

algorithm - 不重复排列

java - 二叉树将值插入节点中。 java