I have interviewed more than a dozen advanced front-ends, but I can't even write (flat data structure to Tree)

Click on the above to view the details of the specific topic. There is a lot to do with flattening trees, but I have never written about flattening trees. interesting. I saw it in the morning and made a handwriting record.
The flat data is as follows:

 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},
]

The output is as follows, an infinite level tree:

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

Answers written by yourself

 const flap2Tree = (flapArr)=>{
    //递归根据pid找父
    const findByPid = (pid, data)=> {
        for(let i=0; i<data.length; i++){
           if( data[i].id === pid ) {
               return data[i];
           }else if(data[i].children && data[i].children.length){
               return pidFindParent(pid, data[i].children);
           }
        }
    }

    let resTree = [];
    flapArr.forEach( t => {
        let myParent = findByPid(t.pid, afterArr); 
        if(myParent){
            myParent.children || (myParent.children = []); //初始化
            myParent.children.push(t);
        }else{
            resTree.push(t);
        }
    })
    return resTree;
}
flap2Tree(arr);

Learn Blogger Optimal Performance Methods

 function arrayToTree(items) {
  const result = [];   // 存放结果集
  const itemMap = {};  // 
  for (const item of items) {
    const id = item.id;
    const pid = item.pid;

    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }

    const treeItem =  itemMap[id];

    if (pid === 0) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}

Jerry
481 声望203 粉丝

学习的付出 从不欺人。记忆总是苦,写总结最牢固