[英]Algorithm to convert a table data to hierarchical tree data using Javascript ECMAScript 6
我有一個JSON表數據,並希望轉換為JSON樹數據,如下所示。 我正在尋找一種有效的JavaScript算法,使用任何新的ECMAScript 6運算符或帶有函數方法的語句(不是通過ES5的標准遞歸算法)?
表數據:
[
{
"Children":"4th Grand Father"
},
{
"Name":"4th Grand Father",
"Children":"3rd Grand Father"
},
{
"Name":"3rd Grand Father",
"Children":"2nd Grand Father"
},
{
"Name":"2nd Grand Father",
"Children":"Grand Father"
},
{
"Name":"Grand Father",
"Children":"Father"
},
{
"Name":"Grand Father",
"Children":"Uncle"
},
{
"Name":"Uncle",
"Children":"Cousin"
},
{
"Name":"Father",
"Children":"Brother"
},
{
"Name":"Father",
"Children":"Me"
}
]
樹數據:
[
{
"Name": "4th Grand Father",
"Children": [
{
"Name": "3rd Grand Father",
"Children": [
{
"Name": "2nd Grand Father",
"Children": [
{
"Name": "Grand Father",
"Children": [
{
"Name": "Father",
"children": [
{
"Name": "Brother"
},
{
"Name": "Me"
}
]
},
{
"Name": "Uncle",
"children": [
{
"Name": "Cousin"
}
]
}
]
}
]
}
]
}
]
}
]
您可以使用此ES6函數,該函數使用Map
,箭頭函數,析構參數賦值。 您甚至可以通過擴展語法替換concat
調用,但我認為這不會帶來任何好處:
const makeTree = (data) => { const hash = data.reduce ( (acc, {Name, Children}) => acc.set(Name, (acc.get(Name) || []).concat(Children)) , new Map ); const recurse = (Name) => hash.has(Name) ? { Name, Children: hash.get(Name).map(recurse) } : { Name }; return recurse(undefined).Children; } // Sample data const data = [ { "Children":"4th Grand Father" }, { "Name":"4th Grand Father", "Children":"3rd Grand Father" }, { "Name":"3rd Grand Father", "Children":"2nd Grand Father" }, { "Name":"2nd Grand Father", "Children":"Grand Father" }, { "Name":"Grand Father", "Children":"Father" }, { "Name":"Grand Father", "Children":"Uncle" }, { "Name":"Uncle", "Children":"Cousin" }, { "Name":"Father", "Children":"Brother" }, { "Name":"Father", "Children":"Me" } ]; const result = makeTree(data); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
哈希變量是從空的Map
構建的,將記錄添加到由Name鍵入的記錄中。 鏈接到每個鍵的值是子信息,作為數組。 遇到相同的Name (即acc.get(Name)
返回某些內容)時,子項將添加到已存在的數組中,否則( || []
)將創建一個空數組,並將子項添加到該數組中。
一旦哈希完成,層次結構的頂部將由其缺少的名稱 ( undefined
)獲取,並且通過遞歸,子項將在哈希中查找並添加到最終對象中。
由於結果對象是具有Children數組的對象,並且所需的結果實際上是該數組,因此返回的是Children屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.