我想在 JavaScript 中創建嵌套陣列。我將得到這樣的物件作為輸入:
[{size: 12, "text": "aa"}, {size: 11, "text": "ab"}, {size: 10, "text": "ac"}, {size: 12, "text": "ad"}...]
我想比較大小并創建類似下面給出的結構的陣列。我想使用參考來創建相同的內容,但 JavaScript 沒有參考。o/p 陣列將是這樣的:
[{
"size": 12,
"text": "a",
"childrens": [{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
},
{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
}
]
},
{
"size": 12,
"text": "a",
"childrens": [{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
},
{
"size": 11,
"text": "a",
"childrens": [{
"size": 10,
"text": "a",
"childrens": [{
"size": 9,
"text": "a",
"childrens": []
}]
},
{
"size": 10,
"text": "a",
"childrens": []
}
]
}
]
}
]
我試過這個:
let start = [];
inp.forEach(key => {
let found = false;
while(!found) {
if(start.length === 0 || start[start.length - 1].size === key.size || key.size > start[start.length - 1].size ) {
start.push({...key, childrens: []})
found = true;
}
else if(start[start.length - 1].size > key.size) {
start = start[start.length - 1].childrens;
}
}
})
但是在這方面我知道我正在重新分配開始,這似乎是錯誤的。那么如何創建上面給出的陣列結構呢?提前致謝。
uj5u.com熱心網友回復:
let inputArr = [{size: 12, "text": "aa"}, {size: 11, "text": "ab"}, {size: 10, "text": "ac"}, {size: 12, "text": "ad"}] let outputArr = []; let findPlace = (output, elem) => { if (output.length === 0) { output.push(elem) } else { let latestOuputElem = output[output.length - 1] if (elem.size >= latestOuputElem.size) { output.push(elem) } else { if (!latestOuputElem.childrens) { latestOuputElem.childrens = [] } findPlace(latestOuputElem.childrens, elem) } } } inputArr.forEach(elem => findPlace(outputArr, elem)) // result // outputArr = [{"size":12,"text":"aa","childrens":[{"size":11,"text":"ab","childrens":[{"size":10,"text":"ac"}]}]},{"size":12,"text":"ad"}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/339110.html
標籤:javascript 节点.js 数组
上一篇:python中的嵌套陣列
