如何在 Javascript 中将字符串数组转换为特定的树结构

2024-05-09

我从后端获取文件路径列表,它代表文件夹结构,如下所示:

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

路径的长度是任意的。为了使用文件树组件(角度2树组件 https://github.com/500tech/angular-tree-component)我需要将这些数据转换为以下格式 https://angular2-tree.readme.io/docs/options-1:

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

I think转换数据最有效的方法是

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

步骤1:

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": {}
    }
}

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

有几个例子,例如this https://stackoverflow.com/questions/47062922/how-to-get-all-keys-with-values-from-nested-objects/47063174 or that https://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objectsSO,但我无法理解如何使它们适应我的需求。


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

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; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Javascript 中将字符串数组转换为特定的树结构 的相关文章

随机推荐