Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • D009-递归类

D009-递归类

let arr = [
    {id: 1, name: '部门1', pid: 0},
    {id: 2, name: '部门2', pid: 1},
    {id: 3, name: '部门3', pid: 1},
    {id: 4, name: '部门4', pid: 3},
    {id: 5, name: '部门5', pid: 4},
]



[
    {
        "id": 1,
        "name": "部门1",
        "pid": 0,
        "children": [
            {
                "id": 2,
                "name": "部门2",
                "pid": 1,
                "children": []
            },
            {
                "id": 3,
                "name": "部门3",
                "pid": 1,
                "children": [
                    // 结果 ,,,
                ]
            }
        ]
    }
]


const getChildren = (data,result,pid) => {
  for(let item in data) {
    if(item.pid === pid) {
      let itemInfo = {
        ...item,
        children:[]
      }
      result.push(itemInfo)
      getChildren(data,itemInfo.children,itemInfo.id)
    }
  }
}


let arrayToTree = (data,pid) => {
  let result = [];
  getChildren(data,result,pid)
  return result
}

方法2

let arr = [
{id: 1, name: '部门1', pid: 0},
{id: 2, name: '部门2', pid: 1},
{id: 3, name: '部门3', pid: 1},
{id: 4, name: '部门4', pid: 3},
{id: 5, name: '部门5', pid: 4},
]
const foo = (arr) => {
    const result = { }
    const ret = []
    // 序列化层级
    arr.forEach((item) => {
        const { pid } = item
        if (result[pid]) result[pid].push(item)
        else result[pid] = [item]
    })
    // 设定初始层级 pid:0,数组
    ret.push(...result['0'])
    // 递归查找
    var fn = (arr) => {
        arr.forEach(item => {
            const { id } = item
            const children = result[id]
            if (children) {
              item.children = children
              fn(children)
            }
        })
        return ret
    }
    return fn(ret)
}
foo(arr)
Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人