簡體   English   中英

如何將數組數組轉換為深嵌套樹視圖

[英]How to convert array of arrays into deep nested tree view

我正在通過將路徑數組轉換為樹視圖數據結構來構建樹視圖。 這就是我想要做的事情:

// routes are sorted.
let routes = [
    ['top', '1.jpg'],
    ['top', '2.jpg'],
    ['top', 'unsplash', 'photo.jpg'],
    ['top', 'unsplash', 'photo2.jpg'],
    ['top', 'foo', '2.jpg'],
    ['top', 'foo', 'bar', '1.jpg'],
    ['top', 'foo', 'bar', '2.jpg']
];

into 

let treeview = {
  name: 'top', child: [
    {name: '1.jpg', child: []},
    {name: '2.jpg', child: []},
    {name: 'unsplash', child: [
        {name: 'photo.jpg', child: []},
        {name: 'photo2.jpg', child: []}
    ]},
    {name: 'foo', child: [
        {name: '2.jpg', child: []},
        {name: 'bar', child: [
            {name: '1.jpg', child: []},
            {name: '2.jpg', child: []}
        ]}
    ]}
]}

現在我已成功通過此方法轉換單個數組項,但無法對多個數組執行此操作。 另請注意,嵌套的treeview不包含重復項。

function nest(arr) {
    let out = [];
    arr.map(it => {
        if(out.length === 0) out = {name: it, child: []}
        else {
            out = {name: it, child: [out]}
        }
    });
    return out;
}

您可以使用嵌套哈希表來訪問路由,並將數組作為結果集。 如果只有一個根元素,則可以獲取結果數組的第一個元素。

 var routes = [['top', '1.jpg'], ['top', '2.jpg'], ['top', 'unsplash', 'photo.jpg'], ['top', 'unsplash', 'photo2.jpg'], ['top', 'foo', '2.jpg'], ['top', 'foo', 'bar', '1.jpg'], ['top', 'foo', 'bar', '2.jpg']], result = [], temp = { _: result }; routes.forEach(function (path) { path.reduce(function (level, key) { if (!level[key]) { level[key] = { _: [] }; level._.push({ name: key, children: level[key]._ }); } return level[key]; }, temp); }); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

ES6沒有臨時對象,但是帶有路徑名的命名對象的搜索。

 var routes = [['top', '1.jpg'], ['top', '2.jpg'], ['top', 'unsplash', 'photo.jpg'], ['top', 'unsplash', 'photo2.jpg'], ['top', 'foo', '2.jpg'], ['top', 'foo', 'bar', '1.jpg'], ['top', 'foo', 'bar', '2.jpg']], result = []; routes.forEach(function (path) { path.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; } 

暫無
暫無

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

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