我需要創建能夠將平面對象轉換爲遞歸對象的功能。這是我的例子: 我有平面數組:將平面結構轉換爲分層結構
var flatArray = [
{
Description: "G",
guid: "c8e63b35",
parent: null,
},
{
Description: "Z",
guid: "b1113b35",
parent: "c8e63b35",
},
{
Description: "F",
guid: "d2cc2233",
parent: "b1113b35",
},
{
Description: "L",
guid: "a24a3b1a",
parent: null,
},
{
Description: "K",
guid: "cd3b11caa",
parent: "a24a3b1a",
},
]
的結果應該是:
recursiveArray = [
{
Description: "G",
guid: "c8e63b35",
parent: null,
Children: [
{
Description: "Z",
guid: "b1113b35",
parent: "c8e63b35",
Children: [
{
Description: "F",
guid: "d2cc2233",
parent: "b1113b35",
}
]
},
]
},
{
Description: "L",
guid: "a24a3b1a",
parent: null,
Children: [
{
Description: "K",
guid: "cd3b11caa",
parent: "a24a3b1a",
}
}
]
請幫我看看這樣做的方式。一個有效的算法將不勝感激,因爲我有理解如何正確地做到這一點的問題。在每種情況下,我需要爲遞歸結構中的checked元素查找特定位置,並將其推送到finded元素children數組中。我認爲這很愚蠢和低效。有什麼辦法可以做到這一點快速和高效?
編輯:遞歸數組格式錯誤。現在應該沒問題。 我的數組沒有以任何方式排序。
,你可以這樣做: 'VAR recoursiveArray = []; recoursiveArray.push(flatArray [0]);recoursiveArray [0] .children = []; recoursiveArray [0] .children.push(flatArray [1]);' –
不應該''L''對象有''c8e63b35''作爲它的父類,而不是'null'? – Oka
是你的數組以某種方式排序? – franciscod