本篇文章小编给大家分享一下js实现树形数据转成扁平数据代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
利用递归的方法循环树形数组,当遇到有children的对象再次调用递归函数循环children数组,每次循环的数据放入一个提前声明好的数组里,等所有递归函数执行完,这个数组即是想要得到的扁平数据数组。
let res = []
const fn = (source)=>{
source.forEach(el=>{
res.push(el)
el.children && el.children.length>0 ? fn(el.children) : ""
})
}
示例1
let res = [] // 用于存储递归结果(扁平数据)
// 递归函数
const fn = (source)=>{
source.forEach(el=>{
res.push(el)
el.children && el.children.length>0 ? fn(el.children) : "" // 子级递归
})
}
// 树形数据
const arr = [
{ id: "1", rank: 1 },
{ id: "2", rank: 1,
children:[
{ id: "2.1", rank: 2 },
{ id: "2.2", rank: 2 }
]
},
{ id: "3", rank:1,
children:[
{ id: "3.1", rank:2,
children: [
{ id:'3.1.1', rank:3,
children:[
{ id: "3.1.1.1", rank: 4,
children:[
{ id: "3.1.1.1.1", rank: 5 }
]
}
]
}
]
}
]
}
]
fn(arr) // 执行递归函数
console.log(res) // 查看结果
结果:
推荐ASP超速入门视频教程
CLAUDE.md 引入 AGENTS.md,Codex 与 Claude Code 会共享同一套规则吗?
借助 AI 梳理陌生代码库:一套分阶段项目导览流程
从 LangChain 迁移到 LangGraph:重构 RAG 知识库流程
读完开源 AI Agent 源码,我重新审视了文件验收机制
从字符串约定到 LangChain:拆解 LLM 的 Tool Calling 流程