簡體   English   中英

如何在Javascript中將字符串數組轉換為特定的樹結構

[英]How to transform array of strings into specific tree structure in Javascript

我從后端得到一個文件路徑列表,它代表一個文件夾結構,如下所示:

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

路徑的長度是任意的。 為了使用文件樹組件( angular2-tree-component ),我需要將此數據轉換為以下格式

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

認為轉換數據的最有效方法是

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

我不知道如何從這里開始=如何在所需結構中構建最終數組時迭代所有鍵和值。

在 SO 上有一些這樣那樣的例子,但我無法理解如何使它們適應我的需求。

我會使用兩個嵌套循環,一個用於路徑,一個用於拆分名稱,然后查找名稱或創建新對象。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM