当前位置:网站首页>递归的使用:1.将平铺数组转为树 2.将树转化为平铺数组
递归的使用:1.将平铺数组转为树 2.将树转化为平铺数组
2022-07-27 23:54:00 【不能懒鸭】
平铺数组
const flatData= [
{
id: '1', parentId: 'root', name:'1'},
{
id: '1-1', parentId: '1', name:'1-1'},
{
id: '1-2', parentId: '1', name:'1-2'},
{
id: '1-1-1', parentId: '1-1', name:'1-1-1'},
{
id: '1-1-2', parentId: '1-1', name:'1-1-2'},
{
id: '1-2-1', parentId: '1-2', name:'1-2-1'}
];
树形数组targetData
const targetData=[
{
id: '1',
parentId: 'root',
name:'1',
children:[
{
id: '1-1',
parentId: '1',
name:'1-1',
children:[
{
id: '1-1-1',
parentId: '1-1',
name:'1-1-1'
},
{
id: '1-1-2',
parentId: '1-1',
name:'1-1-2'
},
]
},
{
id: '1-2',
parentId: '1',
name:'1-2',
children:[
{
id: '1-2-1',
parentId: '1-2',
name:'1-2-1'
},
]
},
]
},
]
具体代码实现:
1.将平铺数组转为树
关键点: 父亲的id是孩子的parentId
function getTreeData(data,id){
let arr = []
data.forEach((item,index) => {
let children = getTreeData(data,item.id)
if(children.length){
item.children = children
}
arr.push(item)
});
return arr
}
const treeData= getTreeData(flatData, 'root');
console.log('tree', targetArr);
2.将树转化为平铺数组
let flatData= []
function getFlatData(data){
data.forEach((item,index)=>{
if(item.children&&item.children.length){
getTreeFlatData(item.children)
delete item.children
}
flatData.push(item)
})
}
getFlatData(treeData)
console.log(flatData)
边栏推荐
猜你喜欢
随机推荐
“你“想当测试/开发程序员吗?努力发芽的我们......
26. Abstraction and template ideas
Tencent cloud hiflow scene connector
Stock problems 5 times
QT setting Icon
HRD 1. a simple and reliable HRD detection method
Niuke net question brushing training (III)
Qt 绘制系统简介
新安装的pip3,使用出现No module named ‘lsb_release‘的问题
小散量化炒股记|量化系统中数据是源头,教你搭建一款普适的数据源框架
26.抽象化和模板思想
VLAN实验
String
Prediction of charitable donation behavior by EEG multivariate model analysis
ue4 unreal NDisplay插件 简易使用 三折幕 详细...
企业运维实践-使用Aliyun容器镜像服务对海外gcr、quay仓库镜像进行镜像拉取构建
[style set 1] tab
HCIP第十五天
Recursion related exercises
面试题 01.09. 字符串轮转









