我有一個平面陣列,其中每個節點都有一個 ID 和一個其子節點的 ID 陣列:
[
{id: 1, children: [2, 3]},
{id: 2, children: []},
{id: 3, children: [4]},
{id: 4, children: []},
{id: 5, children: []},
]
我如何(最好是在 Javascript 中)創建一個層次結構,其中實際物件作為嵌套的子物件,而不僅僅是它們的 ID?
[
{id: 1, children: [
{id: 2, children: []},
{id: 3, children: [
{id: 4, children: []}
]}
]},
{id: 5, children: []},
]
我嘗試了以下方法,但它只適用于第一層:
function getHierarchyFromFlatArray(nodes) {
const nodeById = new Map(nodes.map(el => [el.id, el]))
for (const node of nodes) {
node.children = node.children.map(id => {
let val = nodeById.get(id)
let idx = nodes.findIndex(item => item.id=== id)
nodes.splice(idx, 1)
return val
})
}
return nodes
}
uj5u.com熱心網友回復:
這是解決問題的一種方法。首先構建一個Map參考id值的node值。id如果其值存在于 Map中,則處理串列中的每個節點(遞回地用樹替換子串列,同時從 Map 中洗掉這些節點) 。
const nodes = [
{id: 1, children: [2, 3]},
{id: 2, children: []},
{id: 3, children: [4]},
{id: 4, children: []},
{id: 5, children: []},
]
const nodemap = new Map(nodes.map(n => [n.id, n]));
const tree = (node) => {
nodemap.delete(node.id);
return node.children.length ? {
id : node.id,
children : node.children.map(c => tree(nodemap.get(c)))
}
: node
}
result = []
nodes.forEach(node => {
if (nodemap.has(node.id)) result.push(tree(node))
})
console.log(result)
uj5u.com熱心網友回復:
腳步:
- 創建每個節點到其父節點的映射(
undefined對于根節點)。 - 清除子陣列并開始將每個節點附加到其父節點的子陣列。
undefined最后回傳在我們的映射中具有父鍵的節點。
const getHierarchyFromFlatArray = (nodes) => {
const nodeById = {}
const parent = {}
nodes.forEach((node) => {
nodeById[node.id] = node
node.children.forEach((child) => {
parent[child] = node.id
})
node.children = []
})
nodes.forEach((node) => {
const parentId = parent[node.id]
// ? If current node is the child of some other node
if (parentId && nodeById[parentId]) {
nodeById[parentId].children.push(node)
}
})
return nodes.filter((node) => parent[node.id] === undefined)
}
const input = [
{id: 1, children: [2, 3]},
{id: 2, children: []},
{id: 3, children: [4]},
{id: 4, children: []},
{id: 5, children: []},
]
const output = getHierarchyFromFlatArray(input)
console.log(output)
/*
output = [
{id: 1, children: [
{id: 2, children: []},
{id: 3, children: [
{id: 4, children: []}
]}
]},
{id: 5, children: []},
]
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/460027.html
標籤:javascript 数组 等级制度
