JS树状结构算法
JS通过数组组织树状结构
核心代码
const list = [ { id: "1", name: "目录1", parentId: "0" }, { id: "2", name: "目录1-1", parentId: "1" }, { id: "3", name: "目录1-2", parentId: "1" }, { id: "4", name: "目录1-3", parentId: "1" }, { id: "5", name: "目录1-3-1", parentId: "4" }, { id: "6", name: "目录2", parentId: "0" }, { id: "7", name: "目录3", parentId: "0" }, { id: "8", name: "目录3-1", parentId: "7" }, ]; const m = treeData(list); console.log(m); /** * * @param {*} source 列表 * @param {*} rootID 最外层ID * @param {*} id 判断唯一 * @param {*} parentId 判断父对象ID * @param {*} children 子内容列表 * @returns */ const treeData = ( source, rootID = 0, id = "id", parentId = "parentId", children = "children" ) => { if (!source) return []; let cloneData = JSON.parse(JSON.stringify(source)); return cloneData.filter((father) => { let branchArr = cloneData.filter( (child) => father[id] == child[parentId] ); father[children] = branchArr.length > 0 ? branchArr : []; return father[parentId] == rootID; }); };
通过组织后的代码生成菜单项
内容如果存在侵权,请联系站长进行处理!