一次遍历获取多级嵌套菜单
category_lists = [
{"id": 1, "name": "食品", "parent_id": 0},
{"id": 2, "name": "手机", "parent_id": 0},
{"id": 3, "name": "华为", "parent_id": 2},
{"id": 4, "name": "小米", "parent_id": 2},
{"id": 5, "name": "华为P系列", "parent_id": 3},
{"id": 6, "name": "生食", "parent_id": 1},
{"id": 7, "name": "熟食", "parent_id": 1},
{"id": 8, "name": "华为Mate系列", "parent_id": 3},
{"id": 10, "name": "办公", "parent_id": 0}
]
def getMenu(category_list: list, index: int) -> list:
"""
:param category_list: 菜单列表
:param index: 获取第index菜单级
:return:
"""
# 临时变量存储每级菜单
temp = {}
for i in range(len(category_list)-1, -1, -1):
if not temp.get(category_list[i]["parent_id"]):
category_list[i]["children"] = temp.get(category_list[i]["id"])
temp[category_list[i]["parent_id"]] = [category_list[i]]
else:
category_list[i]["children"] = temp.get(category_list[i]["id"])
temp[category_list[i]["parent_id"]].append(category_list[i])
# print(temp)
# print(res)
# res = temp.get(index)
return temp.get(index)
print(getMenu(category_lists, 0))
print(getMenu(category_lists, 1))
# [{'id': 10, 'name': '办公', 'parent_id': 0, 'children': None}, {'id': 2, 'name': '手机', 'parent_id': 0, 'children': [{'id': 4, 'name': '小米', 'parent_id': 2, 'children': None}, {'id': 3, 'name': '华为', 'parent_id': 2, 'children': [{'id': 8, 'name': '华为Mate系列', 'parent_id': 3, 'children': None}, {'id': 5, 'name': '华为P系列', 'parent_id': 3, 'children': None}]}]}, {'id': 1, 'name': '食品', 'parent_id': 0, 'children': [{'id': 7, 'name': '熟食', 'parent_id': 1, 'children': None}, {'id': 6, 'name': '生食', 'parent_id': 1, 'children': None}]}]
# [{'id': 7, 'name': '熟食', 'parent_id': 1, 'children': None}, {'id': 6, 'name': '生食', 'parent_id': 1, 'children': None}]