[英]Build a Tree from Flat Array
這是一個由 API 返回的列表,需要將其轉換為可以顯示的樹,以便用戶可以 select 獲得所需的權限。
const list = [
{
resource: 'User',
action: 'Create',
id: 1,
},
{
resource: 'User',
action: 'Edit',
id: 2,
},
{
resource: 'User',
action: 'Delete',
id: 3,
},
{
resource: 'Utility.Rule',
action: 'Create',
id: 4,
},
{
resource: 'Utility.Rule',
action: 'Edit',
id: 5,
},
{
resource: 'Utility.Config',
action: 'Create',
id: 6,
},
];
並且需要轉換成一棵樹
{
"id": "root",
"name": "MyTree",
"children": [
{
"id": "User",
"name": "User",
"children": [
{
"id": "1",
"name": "Create"
},
{
"id": "2",
"name": "Edit"
},
{
"id": "3",
"name": "Delete"
}
]
},
{
"id": "Utility",
"name": "Utility",
"children": [
{
"id": "Rule",
"name": "Rule",
"Children": [
{
"id": "4",
"name": "Create"
},
{
"id": "5",
"name": "Edit"
}
]
},
{
"id": "Config",
"name": "Config",
"children": [
{
"id": "6",
"name": "Create"
}
]
}
]
}
]
}
我嘗試了不同的方法,如 Map 並減少但沒有得到想要的 output。
const arrayToTree = (arr, parent = 'User') =>
arr.filter(item => item.parent === parent)
.map(child => ({ ...child, children: arrayToTree(arr,
child.index) }));
arrayToTree(list, 'User')
//This gives me stackoverflow error.
我嘗試的其他選項是首先構建 map
function list_to_tree(list) {
var map = {}, node, roots = [], i;
for (i = 0; i < list.length; i += 1) {
map[list[i].id] = i; // initialize the map
list[i].children = []; // initialize the children
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.parentId !== "0") {
// if you have dangling branches check that map[node.parentId] exists
list[map[node.parentId]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
如果我能對如何構造主節點然后添加子節點有所了解,那就太好了。
我想出的解決方案是遍歷列表,用“。”分割每個資源。 如果不在父節點的子節點中,則為每個資源目錄添加一個節點
const list = [ { resource: 'User', action: 'Create', id: 1 }, { resource: 'User', action: 'Edit', id: 2 }, { resource: 'User', action: 'Delete', id: 3 }, { resource: 'Utility.Rule', action: 'Create', id: 4 }, { resource: 'Utility.Rule', action: 'Edit', id: 5 }, { resource: 'Utility.Config', action: 'Create', id: 6 }, ]; function arrayToTree(list, rootNode = { id: 'root', name: 'MyTree' }) { const addChild = (node, child) => ((node.children?? (node.children = [])).push(child), child); for (const { id, action, resource } of list) { const path = resource.split('.'); const node = path.reduce( (currentNode, targetNodeId) => currentNode.children?.find(({ id }) => id === targetNodeId)?? addChild(currentNode, { id: targetNodeId, name: targetNodeId }), rootNode ); addChild(node, { id: String(id), name: action }); } return rootNode; } console.log(arrayToTree(list));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.