獲取上級節點,下級節點,children格式

type FindIdStruct struct { Id int ParentId int } type MenuRespData struct { Id int Children []MenuRespData } func findParentIds(item FindIdStruct, total []FindIdStruct) []int { parentIds := []int{} for _, v := range total { if v.Id == item.ParentId { parentIds = append(parentIds, v.Id) parentIds = append(parentIds, findParentIds(v, total)...) break } } return parentIds } func findChildIds(item FindIdStruct, total []FindIdStruct) []int { childIds := []int{} for _, v := range total { if v.ParentId == item.Id { childIds = append(childIds, v.Id) childIds = append(childIds, findChildIds(v, total)...) } } return childIds } func tree(parentId int, total []FindIdStruct) []MenuRespData { res := make([]MenuRespData, 0) for _, v := range total { if v.ParentId == parentId { children := tree(v.Id, total) node := MenuRespData{ Id: v.Id, Children: children, } res = append(res, node) } } return res }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章