用js把列表转换为树结构
时间: 2023-11-27 20:54:07 浏览: 65
将一个列表转换成树结构可以用递归来实现。我假设列表中的每个项都有一个 `id` 和一个 `parentId` 属性,`parentId` 指向其父级节点的 `id`。
下面是一个示例代码:
```javascript
function listToTree(list) {
const map = {};
const roots = [];
// 先把每个节点的引用保存在 map 中
list.forEach(item => {
map[item.id] = { ...item, children: [] };
});
// 把每个节点挂到它的父节点上
list.forEach(item => {
const parent = map[item.parentId];
if (parent) {
parent.children.push(map[item.id]);
} else {
roots.push(map[item.id]);
}
});
return roots;
}
```
这个函数接收一个列表作为参数,并返回一个树结构数组,其中每个节点都包含一个 `children` 属性,存放其子节点的数组。
这里的基本思路是先遍历列表,把每个节点的引用保存在 `map` 对象中。然后再遍历列表,把每个节点挂到它的父节点上,如果没有父节点则将其添加到根节点数组中。
使用示例:
```javascript
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.2.1', parentId: 3 },
{ id: 5, name: 'Node 2', parentId: null },
];
const tree = listToTree(list);
console.log(tree);
```
输出:
```javascript
[
{
id: 1,
name: 'Node 1',
parentId: null,
children: [
{
id: 2,
name: 'Node 1.1',
parentId: 1,
children: [],
},
{
id: 3,
name: 'Node 1.2',
parentId: 1,
children: [
{
id: 4,
name: 'Node 1.2.1',
parentId: 3,
children: [],
},
],
},
],
},
{
id: 5,
name: 'Node 2',
parentId: null,
children: [],
},
]
```
阅读全文
相关推荐

















