我在將深度串列轉換為嵌套物件時遇到了一些問題。
例如,我有一個這樣的串列:
"depth"/span>。[ 0, 1, 2, 3, 3, 2, 3, 3,[/span>]。
而我需要想出一個遞回函式來產生一個這樣的物件:
。"depth": [
{
"type": 0,
"children": [
{
"type": 1,
"children": [
{
"type": 2,
"children":[
{ "type": 3, "children": []},
{ "type": 3, "children": []},
]
},
{
"type:": 2,
"children":[
{ "type": 3, "children": []},
{ "type": 3, "children": []},
{ "type": 3, "children": []},
]
}
]
}
]
}
]
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
因此,這里的規則是,較低的數字是父母,較高的數字是前面較低數字的兄弟姐妹。
到目前為止,我想到的是:
。const depth = [0, 1, 2, 3, 3, 2, 3, 3]
//開始回圈瀏覽深度中的所有數字。
for (let i = 0; i < depth.length; i ) { /depth.length
//當我回圈時,我只想看我已經探索過的陣列。
//這樣我就可以找到在陣列中低1的父類。
let getParent = depth.slice(0, i). lastIndexOf(depth[i] - 1) //last lower array的位置。
//這里我檢查當前的深度項是否大于當前陣列中較低的項。
if (depth[i] > depth[getParent]) {
console.log(depth[i] " Nesting into " depth[getParent] ) //是那個專案的孩子。
}
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
我認為這成功地將子節點映射到父節點。但是現在我被卡住了,無法產生我想要的結果。
如果有人有建議,我將非常感激。
謝謝
uj5u.com熱心網友回復:
當使用Map或字典(物件)來檢索父類時,創建一棵樹會更容易。在將整個樹還原為Map之后,檢索根,它持有整個樹。
。const createItem = (type) => ({ type, children: [] })
const fn = (arr, root) => arr. reduce((acc, d) =>/span> {
const parent = d - 1
const item = createItem(d)
if(d !==root && !acc.has(parent)) acc.set(parent, createItem(parent)
if(d !==root) acc.get(parent).children.push( item)
return acc.set(d, item)。
}, new Map()).get(root)。
const depth = [0, 1, 2, 3, 3, 2, 3, 3, 3 ]
const result = fn(depth, 0)。
console.log(result)
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
由于你是按預先的順序獲得資料,你實際上不需要一個地圖:
CodePudding由于你是按預先的順序獲得資料,你實際上不需要一個地圖
。function convert(data) {
let i = 0;
function getChildren(type) {
let children = [] 。
while (data[i] ==type) {
i ;
children.push({
型別。
children: getChildren(type 1)
});
}
return children;
}
return getChildren(0)。
}
let data = [0, 1, 2, 3, 3, 2, 3, 3, 3】。]
console.log(convert(data));
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/313049.html
標籤:
