-
需求: 实现树状数据结构转为数组
-
现有一树状数据结构
const data = [ { id: 1, pid: null, title: '研发部', children: [ { id: 5, title: '前端研发部', pid: 1 }, { id: 6, title: '后端研发部', pid: 1 }, { id: 7, title: '算法研发部', pid: 1 }, ], }, { id: 2, pid: null, title: '开发部', children: [ { id: 8, title: '前端开发部', pid: 2 }, { id: 9, title: '后端开发部', pid: 2 }, { id: 10, title: '算法开发部', pid: 2 }, ], }, { id: 3, title: '市场部', pid: null }, { id: 4, title: '销售部', pid: null }, ];
-
实现 treeToArray 函数,将树状数据结构转为下面的格式
const data = [ { id: 1, title: '研发部', pid: null, }, { id: 2, title: '开发部', pid: null, }, { id: 3, title: '市场部', pid: null, }, { id: 4, title: '销售部', pid: null, }, { id: 5, title: '前端研发部', pid: 1, }, { id: 6, title: '后端研发部', pid: 1, }, { id: 7, title: '算法研发部', pid: 1, }, { id: 8, title: '前端开发部', pid: 2, }, { id: 9, title: '后端开发部', pid: 2, }, { id: 10, title: '算法开发部', pid: 2, }, ];
-
方法1:
function treeToArray1(array) { const result = []; array.forEach((item) => { if (item.children) { // 得到push进去最后一位成员的位置 从1开始 let index = result.push(item, ...item.children); // 删除children属性 delete result[index - item.children.length - 1].children; } else { result.push(item); } }); return result; }
-
方法2
function treeToArray2(array) { return array.reduce((prev, cur) => { if (cur.children) { // 删除chidren项 因为push得到的是push进去的成员在第几个位置 从1开始 因此要减1 delete prev[prev.push(cur, ...cur.children) - cur.children.length - 1].children; } else { prev.push(cur); } return prev; }, []); }
JS面试题【算法】 - 树转数组
于 2022-02-14 12:51:13 首次发布