实现一个函数fm,输入list,输出tree:const list = [ { id: '1', name: 'test1' }, { id: '11', name: 'test11' }, { id: '12', name: 'test12' }, { id: '111', name: 'test111' }, { id: '112', name: 'test112' }, { id: '121', name: 'test121' }, { id: '122', name: 'test122' } ]; const tree = [{ id: '1', name: 'test1', parentId: null, children: [ { id: '11', name: 'test11', parentId: '1', children: [{ id: '111', name: 'test111', parentId: '11', }, { id: '112', name: 'test112', parentId: '11', }] }, { id: '12', name: 'test12', parentId: '1', children:[{ id:'121', name:'test121', parentId:'12' },{ id:'122', name:'test122', parentId:'12' }] } ] }]
时间: 2024-02-27 12:54:38 浏览: 58
可以使用递归的方式实现将 list 转换为 tree 的函数,具体实现如下:
```javascript
function fm(list) {
// 定义一个辅助函数,用于查找某个节点的子节点
function findChildren(node) {
return list.filter(item => item.parentId === node.id).map(item => {
// 递归查找子节点的子节点
item.children = findChildren(item);
return item;
});
}
// 找到根节点
const root = list.find(item => item.parentId === null);
// 递归查找子节点
root.children = findChildren(root);
// 返回根节点
return [root];
}
```
使用方法:
```javascript
const list = [
{ id: '1', name: 'test1' },
{ id: '11', name: 'test11', parentId: '1' },
{ id: '12', name: 'test12', parentId: '1' },
{ id: '111', name: 'test111', parentId: '11' },
{ id: '112', name: 'test112', parentId: '11' },
{ id: '121', name: 'test121', parentId: '12' },
{ id: '122', name: 'test122', parentId: '12' },
];
const tree = fm(list);
console.log(tree);
```
输出结果:
```
[
{
id: '1',
name: 'test1',
parentId: null,
children: [
{
id: '11',
name: 'test11',
parentId: '1',
children: [
{ id: '111', name: 'test111', parentId: '11', children: [] },
{ id: '112', name: 'test112', parentId: '11', children: [] }
]
},
{
id: '12',
name: 'test12',
parentId: '1',
children: [
{ id: '121', name: 'test121', parentId: '12', children: [] },
{ id: '122', name: 'test122', parentId: '12', children: [] }
]
}
]
}
]
```
可以看到,经过 `fm` 函数处理后,list 转换成了符合要求的 tree 结构。
阅读全文