js树结构数据处理成一维数组(递归)

话不多说,直接上代码

const makeList = (roles) => {
  if (!Array.isArray(roles)) {
    return { menus: null,};
  }
  const menus = [];

  const recursion = (dataArr, parentPathname) => {
    dataArr.forEach((data) => {
      if (data && typeof data === 'object' && !Array.isArray(data)) {
        const { type, route, children, ...rest } = data;
        if (type === 1) {
          menus.push({
            type,
            route,
            ...rest,
          });
          if (Array.isArray(children) && children.length > 0) {
            recursion(children, route);
          }
        } 
      }
    });
  }
  recursion(roles, '/');
  return { menus, licenses };
};

你可能感兴趣的:(js)