foreword
When doing projects, it is often encountered that the data returned by the background needs to be converted into a tree structure for display to the user, for example:
This is also an algorithm question that is often tested in front-end interviews. Let's test it together.
step
- Prepare an empty tree object.
- Iterate over each element in the list.
- For each element, find its corresponding parent node according to the parent ID of the element.
- If a parent node is found, the element is added to the parent node's list of children.
- If no parent node is found, a new node is created with the element as its child.
- Repeat steps 2~5 until all elements are traversed.
- Returns the tree object.
code example
const list = [
{ id: 1, name: 'Node 1', parentId: null },
{ id: 2, name: 'Node 1-1', parentId: 1 },
{ id: 3, name: 'Node 1-2', parentId: 1 },
{ id: 4, name: 'Node 1-1-1', parentId: 2 },
{ id: 5, name: 'Node 2', parentId: null },
{ id: 6, name: 'Node 2-1', parentId: 5 },
]
function listToTree(list) {
const map = {} // 用于存储节点 id 与节点的映射关系
const tree = [] // 树的根节点
// 首次遍历,将节点 id 与节点进行映射
list.forEach(node => {
map[node.id] = { ...node, children: [] }
})
// 第二次遍历,构建树结构
list.forEach(node => {
if (node.parentId) {
// 如果存在父级节点,则将当前节点添加到父级节点的子节点列表中
map[node.parentId].children.push(map[node.id])
} else {
// 否则,将当前节点作为根节点
tree.push(map[node.id])
}
})
return tree
}
const tree = listToTree(list)
console.log(tree)
output:
[
{
"id": 1,
"name": "Node 1",
"parentId": null,
"children": [
{
"id": 2,
"name": "Node 1-1",
"parentId": 1,
"children": [
{
"id": 4,
"name": "Node 1-1-1",
"parentId": 2,
"children": []
}
]
},
{
"id": 3,
"name": "Node 1-2",
"parentId": 1,
"children": []
}
]
},
{
"id": 5,
"name": "Node 2",
"parentId": null,
"children": [
{
"id": 6,
"name": "Node 2-1",
"parentId": 5,
"children": []
}
]
}
]
Scenario
1. File System: Organize files and folders in the file system into a tree structure.
2. Organizational structure: In an enterprise, a tree structure can be used to represent the relationship between employees to build an organizational chart.
3. Navigation menu: In the navigation menu of a website or application, a tree structure is usually used to represent different page levels.
4. Comment reply: In social media or forums, users can reply to comments, and this reply relationship can be organized and displayed in a tree structure.
5. Category catalog: Product categories in e-commerce websites, article categories in blogs, etc. can be organized and displayed in a tree structure.