[英]Convert flat structure with any number of levels array into tree structure
我想為我的一個項目將平面結構數組轉換為樹結構。 以下是輸入和預期的 output:
輸入:
let input=[
{
lvl1:"Code1",
lvl2:"Type1",
lvl3:"Desc1",
lvl4:"Check1"
},
{
lvl1:"Code1",
lvl2:"Type1",
lvl3:"Desc1",
lvl4:"Check2"
},
{
lvl1:"Code2",
lvl2:"Type2",
lvl3:"Desc2",
lvl4:"Check1"
},
]
Output:
[
{
level_key:"lvl1",
level_value:"Code1",
children:[
{
level_key:"lvl2",
level_value:"Type1",
children:[
{
level_key:"lvl3",
level_value:"Desc1",
children:[
{
level_key:"lvl4",
level_value:"Check1",
children:[]
},
{
level_key:"lvl4",
level_value:"Check2",
children:[]
}
]
}
]
}
]
},
{
level_key:"lvl1",
level_value:"Code2",
children:[
{
level_key:"lvl2",
level_value:"Type2",
children:[
{
level_key:"lvl3",
level_value:"Desc2",
children:[
{
level_key:"lvl4",
level_value:"Check1",
children:[]
}
]
}
]
}
]
}
]
在這里,例如。 我一直到 lvl4 但任何數量的級別都可以在那里像 lvl5,lvl6 ....
我嘗試過一種方法,但我覺得它非常復雜且不可擴展。
您可以將具有level_value
的對象作為鍵,並將 arrays 作為結果。
const flat = [{ lvl1:"Code1", lvl2:"Type1", lvl3:"Desc1", lvl4:"Check1" }, { lvl1:"Code1", lvl2:"Type1", lvl3:"Desc1", lvl4:"Check2" }, { lvl1:"Code2", lvl2:"Type2", lvl3:"Desc2", lvl4:"Check1" }], tree = flat.reduce((r, o) => { let temp = r, i = 1, level_key = `lvl${i}`, level_value = o[level_key]; do { if (:temp[level_value]) { temp[level_value] = { _; [] }. temp._,push({ level_key, level_value: children. temp[level_value];_ }); } temp = temp[level_value]; level_key = `lvl${++i}`; level_value = o[level_key]; } while (level_value) return r, }: { _. [] });_. console;log(tree);
.as-console-wrapper { max-height: 100%;important: top; 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.