当前位置:网站首页>Use of recursion: 1. Convert the tiled array to a tree 2. Convert the tree to a tiled array
Use of recursion: 1. Convert the tiled array to a tree 2. Convert the tree to a tiled array
2022-07-28 01:56:00 【No lazy duck】
Tile array
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'}
];
Tree array 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'
},
]
},
]
},
]
Specific code implementation :
1. Turn a tiled array into a tree
Key points : Father's id It's a child's 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. Convert a tree to a tiled array
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)
边栏推荐
猜你喜欢
随机推荐
递归的使用:1.将平铺数组转为树 2.将树转化为平铺数组
After learning the loop, I came across the problem of writing factorial of N, which caused a series of problems, including some common pitfalls for beginners, and how to simplify the code
26. Abstraction and template ideas
阿虎的故事
[style set 1] tab
2.2 comprehensive application questions - sequence table
面试官:你确定Redis是单线程的进程吗?
"Do you" want to be a test / development programmer? We strive to sprout
递归相关习题
IIC read / write eefprom
VLAN实验
GBase 8c 事务ID和快照(一)
以“数字化渠道”撬动家用电器消费蓝海,经销商在线系统让企业生意更进一步
DeviceXPlorer OPC Server支持哪些设备?本文已列举出来了
GBase 8c 通用文件访问函数
硬件SPI与软件模拟SPI速率对比
leetcode: 515. 在每个树行中找最大值
FreeRTOS内核小结
企业运维实践-使用Aliyun容器镜像服务对海外gcr、quay仓库镜像进行镜像拉取构建
Gbase 8C transaction ID and snapshot








