生成树数据
先上代码:
/** * 构造树型结构数据 * @param {*} data 数据源 * @param {*} parentId 父节点字段 默认 'parentId' */ export function handleTree(data, parentId) { const initArr = data.filter(q => q.parentId === parentId) return initArr.map(q => ({ ...q, children: handleTree(data, q.menuId) })) }
效果:
初始数据: [ { name: 'z1', menuId: 1, parentId: 0 }, { name: 'z11', menuId: 10, parentId: 1 }, { name: 'z12', menuId: 11, parentId: 1 } ] 结果数据: [ { "name":"z1", "menuId":1, "parentId":0, "children":[ { "name":"z11", "menuId":10, "parentId":1, "children":[ ] }, { "name":"z12", "menuId":11, "parentId":1, "children":[ ] } ] } ]
记录进步!!!
来自:https://www.cnblogs.com/niexianda/p/14482157.html