【问题标题】:How to convert array of arrays into deep nested tree view如何将数组数组转换为深层嵌套树视图
【发布时间】:2018-01-26 18:52:00
【问题描述】:

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

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

现在我已经通过此方法成功转换了单个项目数组,但无法对多个数组执行此操作。另请注意,嵌套树视图不包含重复项。

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

【问题讨论】:

  • 第一个代码是否被剪断了您想要实现的目标并且无法实现?
  • 第一个代码 sn-p 仅对单个项目数组进行嵌套。

标签: javascript algorithm tree grouping


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2014-07-09
    • 2020-12-10
    • 1970-01-01
    • 2016-03-01
    • 2014-10-13
    • 2019-09-23
    相关资源
    最近更新 更多