树结构转数组/数组转树结构

树结构转数组

const listTree = [ { id: 1, name: '部门1', pid: 0, children: [ { id: 2, name: '部门1-1', pid: 1, children: [ { id: 4, name: '部门1-1-1', pid: 2, children: [] } ] }, { id: 3, name: '部门1-2', pid: 1, children: [ { id: 5, name: '部门1-2-1', pid: 3, children: [] } ] } ] }, { id: 6, name: '部门2', pid: 0, children: [ { id: 7, name: '部门2-1', pid: 6, children: [] } ] }, { id: 8, name: '部门3', pid: 0, children: [] } ] const list = [] const listforEach = (list, newList) => { list.forEach((item) => { const info = {} info.id = item.id info.name = item.name info.pid = item.pid newList.push(info) if (item.children.length > 0) { listforEach(item.children, newList) } }) } const bianlishuzu = () => { listforEach(listTree, list) }

  

数组转树结构
const list = [ { id: 1, name: '部门1', pid: 0 }, { id: 2, name: '部门1-1', pid: 1 }, { id: 3, name: '部门1-2', pid: 1 }, { id: 4, name: '部门1-1-1', pid: 2 }, { id: 5, name: '部门1-2-1', pid: 3 }, { id: 6, name: '部门2', pid: 0 }, { id: 7, name: '部门2-1', pid: 6 }, { id: 8, name: '部门3', pid: 0 } ] const listTree = [] const listforEach = (list, listTree, pid) => { let sonlist = [] list.forEach((item) => { if (item.pid == pid) { let par = { id: item.id, name: item.name, pid: item.pid, children: [] } listTree.push(par) } else { sonlist.push(item) } }) listTree.forEach((item) => { listforEach(sonlist, item.children, item.id) }) } const bianlishuzu = () => { listforEach(list, listTree, 0) console.log(listTree) }

  

posted @ 2023-09-20 15:00  web格调  阅读(21)  评论(0编辑  收藏  举报