![](/img/trans.png)
[英]Create a tree from a list of strings containing paths of files - javascript
[英]Create a tree from a list of strings containing paths
請參閱下面的編輯
我想嘗試從路徑列表中創建一棵樹,並從另一個問題在 stackoverflow 上找到了此代碼,它似乎工作正常,但我想刪除空的子數組,而不是讓它們顯示零項。
我嘗試計算 r[name].result 長度,並且只在它大於零時才推送它,但我最終在任何節點上都沒有孩子。
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];
let result = [];
let level = {result};
paths.forEach(path => {
path.split('/').reduce((r, name, i, a) => {
if(!r[name]) {
r[name] = {result: []};
r.result.push({name, children: r[name].result})
}
return r[name];
}, level)
})
console.log(result)
編輯我不想直接詢問我使用它的目的,但如果它有幫助,我正在嘗試創建一個這樣的數組:(這是 ng-zorro 級聯器所需配置的復制粘貼)
const options = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
isLeaf: true
}
]
},
{
value: 'ningbo',
label: 'Ningbo',
isLeaf: true
}
]
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
isLeaf: true
}
]
}
]
}
];
來自像這樣的平面字段數組:
let paths = ["About.vue","Categories/Index.vue","Categories/Demo.vue","Categories/Flavors.vue","Categories/Types/Index.vue","Categories/Types/Other.vue"];
我建議使用不同的方法。
這種方法需要一個對象而不是一個數組來達到更深的層次,並且只有在需要嵌套層次時才分配一個數組。
let paths = ["About.vue", "Categories/Index.vue", "Categories/Demo.vue", "Categories/Flavors.vue", "Categories/Types/Index.vue", "Categories/Types/Other.vue"], result = paths .reduce((parent, path) => { path.split('/').reduce((r, name, i, { length }) => { let temp = (r.children ??= []).find(q => q.name === name); if (!temp) r.children.push(temp = { name, ...(i + 1 === length && { isLeaf: true }) }); return temp; }, parent); return parent; }, { children: [] }) .children; console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.