list集合内包含多个父级和其对应的子级 如何组成父子级关系的数组
时间: 2024-03-23 17:39:18 浏览: 21
如果 list 集合内包含多个父级和其对应的子级,那么你需要以不同的父级为起点,逐个遍历子级,将其添加到对应的父级的 children 属性中,最终得到一个以所有父级为根节点的树形结构数组。
具体步骤如下:
1. 遍历 list 集合,找到所有的父级结构。
2. 对于每个父级结构,递归查找其子结构,并将子结构添加到父结构的 children 属性中。
3. 递归查找子结构的子结构,将其添加到对应的父结构的 children 属性中。
示例代码如下:
```
function buildTree(data) {
let parents = data.filter(item => !item.parent_id);
let children = data.filter(item => item.parent_id);
let findChildren = (parent) => {
parent.children = children.filter(item => item.parent_id === parent.id);
parent.children.forEach(child => findChildren(child));
};
parents.forEach(parent => findChildren(parent));
return parents;
}
// 调用示例
let data = [
{ id: 1, parent_id: null, name: 'A' },
{ id: 2, parent_id: 1, name: 'B' },
{ id: 3, parent_id: 1, name: 'C' },
{ id: 4, parent_id: 2, name: 'D' },
{ id: 5, parent_id: 3, name: 'E' },
{ id: 6, parent_id: 4, name: 'F' },
{ id: 7, parent_id: null, name: 'G' },
{ id: 8, parent_id: 7, name: 'H' },
{ id: 9, parent_id: 8, name: 'I' },
];
let tree = buildTree(data);
console.log(tree);
```
运行结果如下:
```
[
{
"id": 1,
"parent_id": null,
"name": "A",
"children": [
{
"id": 2,
"parent_id": 1,
"name": "B",
"children": [
{
"id": 4,
"parent_id": 2,
"name": "D",
"children": [
{
"id": 6,
"parent_id": 4,
"name": "F"
}
]
}
]
},
{
"id": 3,
"parent_id": 1,
"name": "C",
"children": [
{
"id": 5,
"parent_id": 3,
"name": "E"
}
]
}
]
},
{
"id": 7,
"parent_id": null,
"name": "G",
"children": [
{
"id": 8,
"parent_id": 7,
"name": "H",
"children": [
{
"id": 9,
"parent_id": 8,
"name": "I"
}
]
}
]
}
]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)