当前位置:网站首页>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)
边栏推荐
猜你喜欢

数字经济才是未来经济发展的核心

开源飞控(PX4、ardupilot)

抓包精灵NetCapture APP抓包教程《齐全》

If you are still using WiFi, you will be out: li-fi is better!!!

数商云供应链集采管理系统解决方案:集采系统管理模式,数字化管控企业物资

leetcode: 515. 在每个树行中找最大值

Leetcode high frequency question 128. the longest continuous sequence, which is often tested in interviews with Internet companies

负载均衡SLB

FreeRTOS内核小结

ue4 unreal NDisplay插件 简易使用 三折幕 详细...
随机推荐
Game 302 of leetcode
GBase 8c 快照同步函数
C language · pointer
Favorite songs
白质脑功能网络图论分析:抑郁症分类和预测的神经标记
HCIP第十二天笔记
GBase 8c 事务ID和快照(五)
leetcode: 515. 在每个树行中找最大值
HCIP第十三天笔记
js 哪些情况不能用 JSON.parse 、JSON.stringify深拷贝及一个更好的深拷贝方法
My rich second generation friend
Gbase 8C transaction ID and snapshot (I)
Flink 在 讯飞 AI 营销业务的实时数据分析实践
JS数字精度丢失的原因及解决方案
GBase 8c 备份控制函数(二)
Modify the request path using the streaming API of gateway
day7
机器学习如何做到疫情可视化——疫情数据分析与预测实战
Open source flight control (Px4, ardupilot)
Leetcode: 515. Find the maximum value in each tree row