js 树形结构问题处理?

将如下结构中的type=1的内容提取到父级。层级可能是无限极。

const routes = [
  {
    name: "首页",
    type: 0,
    children: [],
  },
  {
    name: "系统管理",
    type: 0,
    children: [
      {
        name: "用户管理",
        type: 0,
        children: [
          {
            name: "新建用户",
            type: 1,
            children: [],
          },
        ],
      },
      {
        name: "角色管理",
        type: 0,
        children: [
          {
            name: "新建角色",
            type: 1,
            children: [],
          },
          {
            name: "成员管理",
            type: 1,
            children: [],
          },
        ],
      },
    ],
  },
];

期望:

const routes = [
  {
    name: "首页",
    type: 0,
    children: [],
  },
  {
    name: "系统管理",
    type: 0,
    children: [
      {
        name: "用户管理",
        type: 0,
        children: [],
      },
      {
        name: "新建用户",
        type: 1,
        children: [],
      },
      {
        name: "角色管理",
        type: 0,
        children: [],
      },
      {
        name: "新建角色",
        type: 1,
        children: [],
      },
      {
        name: "成员管理",
        type: 1,
        children: [],
      },
    ],
  },
];
阅读 1.3k
1 个回答

大体上这样,细节在修改下

function flatArr(list){
    let pl = []
    let res = list.filter(item => {
        if(Array.isArray(item.children)){
            pl = pl.concat( flatArr(item.children) )
        }
        return item.type === 1
    })
    pl.length && list.push.apply(list, pl)
    return res
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题