如何在Javascript中将字符串数组转换为特定的树结构 [英] How to transform array of strings into specific tree structure in Javascript

查看:87
本文介绍了如何在Javascript中将字符串数组转换为特定的树结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get a list of file paths from the backend, it represents a folder structure and looks like this:

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

路径的长度是任意的.为了使用文件树组件( angular2-tree-component ),我需要将此数据转换为以下格式:

The lengths of the paths are arbitrary. In order to use a file tree component (angular2-tree-component) I need to transform this data into the following format:

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

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

I think the most efficient way to transform the data is to

  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(节点))时,得到以下结果:

When passing "nodes" into the transformToTree function (transformToTree(nodes)), I get the following result:

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

我不知道如何从这里开始=如何在所需结构中构建最终数组时遍历所有键和值.

I don't know how to proceed from here = how to iterate over all the keys and values while building the final array in the required structure.

有一些例子,例如 this,但我无法理解可以使它们适应我的需求.

There are a few examples like this or that on SO, but I was not able to understand how I could adapt them to my needs.

推荐答案

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

I would go with two nested loops, one for pathes and one for the splitted names and find the name or create new objects.

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

这篇关于如何在Javascript中将字符串数组转换为特定的树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆