JS树形数组扁平化
如题,有时候需要对树形数组深层去找符合字段的那一串json,苦于循环找太费劲,索引选择扁平化,找起来方便很多
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | let treeList = [{ id: '1' , name: '水果' , value: 3, children: [{ id: '1-1' , name: '西瓜' , value: 2, children: [{ id: '1-1-1' , name: '西瓜皮' , value: 1, children: [], }, { id: '1-1-2' , name: '西瓜种子' , value: 1, children: [], } ] }, { id: '1-2' , name: '柚子' , value: 1, children: [], }, { id: '1-3' , name: '橘子' , value: 1, children: [], }] }, { id: '2' , name: '肉' , value: 4, children: [{ id: '2-1' , name: '牛肉' , value: 1, children: [{ id: '2-1-2' , name: '和牛肉' , value: 1, children: [], }, { id: '2-1-2' , name: '澳牛肉' , value: 1, children: [], } ], }, { id: '2-2' , name: '羊肉' , value: 1, children: [], }, { id: '2-3' , name: '猪肉' , value: 1, children: [], }, { id: '2-4' , name: '鱼肉' , value: 1, children: [], } ] }, { id: '3' , name: '蔬菜' , value: 2, children: [{ id: '3-1' , name: '大白菜' , value: 1, children: [], }, { id: '3-2' , name: '菠菜' , value: 1, children: [], }] }, ]; console.log(treeList); |
封装函数如下:

//扁平化 /* * bossArr 树形数据 * children 树形数据子数据的属性名, 本项目为 children * */ function extractTree(bossArr, children) { //如果为空 返回空(防止 children 递归报错) if (!Array.isArray(bossArr) && !bossArr.length) return []; let list = []; const getObj = (arr) => { arr.forEach((row) => { let obj = {}; obj = JSON.parse(JSON.stringify(row)); list.push(obj); if (row[children]) { getObj(row[children]); } }); return list; }; return getObj(bossArr); } const newList = extractTree(treeList, 'children'); console.log(newList);
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库