【问题标题】:How to transform array of strings into specific tree structure in Javascript如何在Javascript中将字符串数组转换为特定的树结构
【发布时间】:2020-03-21 19:05:46
【问题描述】:

我从后端得到一个文件路径列表,它代表一个文件夹结构,看起来像这样:

paths = ["path/to/file1.doc", "path/to/file2.doc", "foo/bar.doc]

路径的长度是任意的。为了使用文件树组件(angular2-tree-component),我需要将此数据转换为following format

nodes = [
    {
        "name": "path",
        "children": [
            {
                "name": "to",
                "children": [
                    {"name": "file1.doc"},
                    {"name": "file2.doc"}
                ]
            }
        ]
    },
    {
        "name": "foo",
        "children": [
            {"name": "bar.doc"}
        ]
    }
]

认为转换数据最有效的方法是

  1. 首先将数组与镜像树结构的文件映射,然后再映射到
  2. 迭代每个键以最终确定“子/父”关系。

第一步:

transformToTree(data) {
    const tree = {};
    function addPathsToTree(paths) {
        let map = tree
        paths.forEach(function(item) {
            map[item] = map[item] || {};
            map = map[item];
        });
    }
    data.forEach(function(path) {
        let pathPart = path.split('/');
        addPathsToTree(pathPart);
    });
    return pathTree;
}

将“节点”传递给 transformToTree 函数 (transformToTree(nodes)) 时,我得到以下结果:

{
    "path": {
        "to": {
            "file1.doc": {},
            "file2.doc": {}
        }
    },
    "foo": {
        "bar": {}
    }
}

我不知道如何从这里开始 = 如何在以所需结构构建最终数组时迭代所有键和值。

在 SO 上有一些示例,例如 thisthat,但我无法理解如何使它们适应我的需求。

【问题讨论】:

    标签: javascript angular typescript mapping


    【解决方案1】:

    我会使用两个嵌套循环,一个用于路径,一个用于拆分名称,然后查找名称或创建新对象。

    var paths = ["path/to/file1.doc", "path/to/file2.doc", "foo/bar.doc"],
        result = [];
        
    paths.reduce((r, path) => {
        path.split('/').reduce((o, name) => {
            var temp = (o.children = o.children || []).find(q => q.name === name);
            if (!temp) o.children.push(temp = { name });
            return temp;
        }, r);
        return r;
    }, { children: result });
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

    • 聪明。非常感谢您的帮助!
    猜你喜欢
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多