簡體   English   中英

javascript將嵌套字典轉換為樹狀數組結構

[英]javascript convert nested dictionary to tree like array structure

我有一個字符串輸入示例,格式為-“ abc”,“ ade”等。

我想轉換以“。”分隔的字符串部分。 以樹狀結構表示。

因此,我編寫了以下函數,從這樣的輸入數組創建嵌套的字典對象-

function items_to_tree(items) {
    var arr = {};
    items.forEach(function(item){
        var parts = item.split(".");
        var last = parts.pop();
        var cursor = arr;
        parts.forEach(function(part){
            if(!cursor[part]) cursor[part] = {};
            cursor = cursor[part];
        });
        cursor[last] = {};
    });
    return arr;
}

因此,例如,如果我將以下示例輸入提供給此函數-

var items = ["a.b", "a.c", "b.c", "a.c", "a.c.d", "a.b.d"]

我得到{"a":{"b":{"d":{}},"c":{"d":{}}},"b":{"c":{}}}預期的{"a":{"b":{"d":{}},"c":{"d":{}}},"b":{"c":{}}}

但是,我希望輸出的格式與此類似-

[{name: "a", children: [{name: "b", children: [{name: "d", children: []}]}]}, {name: "c", children: [{name: "d", children: []}]}, {name: "b", children: [{name: "c", children: []}]}]

是否可以通過任何方式修改items_to_tree函數以返回此類輸出,或者可以將items_to_tree [嵌套字典]的中間輸出轉換為類似於javascript對象數組的樹。

您可以在嵌套數組中搜索給定名稱,然后使用該對象或創建一個新對象。

 var items = ["ab", "ac", "bc", "ac", "acd", "abd"], result = []; items.forEach(function (path) { path.split('.').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; } 

我將為最終數據轉換編寫第二個函數。 您的items_to_tree非常通用且可重用。 只需幾行即可將該樹轉換為所需格式:

function tree_to_format(tree) {
  return Object
    .keys(tree)
    .map(k => ({ name: k, children: tree_to_format(tree[k]) }))
};

現在,您可以通過將tree_to_format的結果items_to_treetree_to_format組合所需的功能:

 function items_to_tree(items) { var arr = {}; items.forEach(function(item){ var parts = item.split("."); var last = parts.pop(); var cursor = arr; parts.forEach(function(part){ if(!cursor[part]) cursor[part] = {}; cursor = cursor[part]; }); cursor[last] = {}; }); return arr; } function tree_to_format(tree) { return Object .keys(tree) .map(k => ({ name: k, children: tree_to_format(tree[k]) })) }; console.log( tree_to_format( items_to_tree(["ab", "ac", "bc", "ac", "acd", "abd"]) ) ); // or even: const compose = (f, g) => x => f(g(x)); const items_to_format = compose(tree_to_format, items_to_tree); 

暫無
暫無

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

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