当前位置:网站首页>递归的使用: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)
边栏推荐
猜你喜欢
随机推荐
HRD 1. 一个简单而靠谱的HRD的检测方法
写给去不图床用户的一封信
白质脑功能网络图论分析:抑郁症分类和预测的神经标记
GBase 8c 服务器信号函数
LeetCode 2347. 最好的扑克手牌
抓包精灵NetCapture APP抓包教程《齐全》
集合/容器
普通设备能不能接入TSN时间敏感网络?
Niuke net question brushing training (III)
现货白银如何计算盈亏
IIC读写EEFPROM
Docker builds MySQL master-slave locally
Lambda表达式和Stream流
The story of the third uncle
Niuke multi School Game 3 A, c+ weight segment tree
三舅的故事
Fiddler 手机抓包代理设置(针对华为荣耀60S)
企业运维实践-使用Aliyun容器镜像服务对海外gcr、quay仓库镜像进行镜像拉取构建
Let's move forward together, the 10th anniversary of Google play!
Qt 绘制系统简介









