【蓝桥杯】商城管理系统

仅作记录之用
思路:递归创建根数组和子数组
“我会出手”佬哥的代码

// menuList 仅为示例数据,非实际使用数据,实际使用数据层级不确定(可能是四级五级六级等),数据结构与 menuList 一致
// 1. `parentId` 如果为 `-1`,则表示此条数据为顶级数据。
// 2. `parentId` 为该条数据的父级数据的 `id`。

let menuList = [
  { parentId: -1, name: "添加管理员", id: 10, auth: "admin" },
  { parentId: 10, name: "管理员权限分配", id: 11, auth: "admin-auth" },
  { parentId: -1, name: "商品管理", id: 1, auth: "product" },
  { parentId: 1, name: "商品列表", id: 4, auth: "productList" },
  { parentId: 4, name: "商品分类", id: 5, auth: "category" },
  { parentId: 5, name: "添加分类", id: 8, auth: "addClassification" },
  { parentId: 4, name: "商品上架", id: 6, auth: "product" },
  { parentId: -1, name: "评论管理", id: 2, auth: "comments" },
  { parentId: -1, name: "个人中心", id: 3, auth: "profile" },
];

/**
 * @param {*} menuList 传入的数据
 * @return {*} menus 转化后的树形结构数据,auths 转化后的权限列表数组
 */

const getMenuListAndAuth = (menuList) => {
  // TODO:待补充代码
  let menus = parseMenu(-1, menuList)
  let auths = []
  menuList.forEach(ele => {
    auths.push(ele.auth)
  });
  return { menus, auths }; // menus 转化后的树形结构数据,auths 转化后的权限列表数组
};
function parseMenu(parentId, menuList) {
  let root = []
  for(i = 0; i < menuList.length; i++) {
    if(menuList[i].parentId == parentId) {
      root.push(menuList[i])
    }
  }
  for(i = 0; i < root.length; i++) {
    root[i].children = parseMenu(root[i].id, menuList)
  }
  return root
}

// 请勿删除和修改以下代码
try {
  module.exports = { getMenuListAndAuth };
} catch (e) {}

”厉不厉害你坤哥“佬哥的代码

const getMenuListAndAuth = (menuList) => {
  const tree = (list,pid=-1) => list.filter(i=>i.parentId==pid).map(i=>(i.children = tree(list,i.id),i))
  const menus = tree(menuList)
  const auths = menuList.map(i=>i.auth)
  return { menus, auths }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值