未命名

2021-09-10 15:44:26  暗夜独行者  版权声明:本文为站长原创文章,转载请写明出处


#TypeScript

## 参考案例:

> [JS实现 JSON扁平数据转换树状数据 - _Wang - 博客园 (cnblogs.com)](https://www.cnblogs.com/dnghj/p/12249833.html)
>
> [使用递归遍历并转换树形数据(以 TypeScript 为例) - SegmentFault 思否](https://segmentfault.com/a/1190000011819279)
>
>



## 思路:

输入数据:

```tsx
interface Side_0_2_3 {
id: number;
parentId: null | number;
name: string;
weight: number;
count: number;
}
const lists: Side_0_2_3[] = [
{
id: 0,
parentId: null,
name: "全部",
weight: 0,
count: 29522
},
{
id: 1515,
parentId: 0,
name: "其他",
weight: 99,
count: 8176
}

]
```

输出数据:

```tsx
interface treeData {
title: string | JSX.Element;
key: string;
children?: treeData[]
}
const treeData: treeData[] = [
{
title: 'parent 1',
key: '0-0',
children: [
{
title: 'parent 1-0',
key: '0-0-0',
children: [
{
title: 'leaf',
key: '0-0-0-0',
},
{
title: 'leaf',
key: '0-0-0-1',
},
],
},
{
title: 'parent 1-1',
key: '0-0-1',
children: [{
title: <span style={{ color: '#1890ff' }}>sss</span>,
key: '0-0-1-0'
}],
},
],
},
];

```

这里需要用到广度遍历和深度遍历两个知识点。



递归



```tsx
format(){

for(let i = 0;i<data.length;i++){

}
}
```






最新评论: