天天看點

将有父子關系的數組資料轉換成樹形結構

1問題

使用vue開發項目時使用到了element ui元件的樹形元件,需要的資料是有樹形結構的資料,但是背景傳回的資料是有父子關系的數組,需要對數組進行處理是資料能被樹形控件識别

原資料:

sider:[
    {label:"一級目錄1",id:1,path:"",parentid:0},
    {label:"一級目錄2",id:2,path:"",parentid:0},
    {label:"二級目錄1-1",id:3,path:"one",parentid:1},
    {label:"二級目錄1-2",id:4,path:"two",parentid:1},
    {label:"三級目錄2-1",id:5,path:"three",parentid:2},
    {label:"三級目錄2-2",id:6,path:"four",parentid:2}
]
           

2處理方法

dataDeal(treedata){//treedata為原數組
  //最頂級資料(沒有父節點)
  var parents=treedata.filter(value=>value.parentid==0);
  //有父節點的資料
  var children = treedata.filter(value=>value.parentid!==0);
  //實作的方法
  var translator = (parents,children)=>{
    //周遊父節點
    parents.forEach(parent=>{
      //周遊子節點
      children.forEach((child,index)=>{
        //如父節點有對應的子節點,就在父節點對象中添加children屬性,并将子節點作為屬性值,然後子節點作為父節點一層一層周遊下去
        if(child.parentid==parent.id){
          let temp = JSON.parse(JSON.stringify(children));
          temp.splice(index, 1)
          translator([child], temp);
          typeof parent.children !== 'undefined' ? parent.children.push(child) : parent.children = [child]
        }
      })
    })
  }
  translator(parents,children);
  return parents;
}
           

3結果

處理前資料:

将有父子關系的數組資料轉換成樹形結構

處理後資料:

将有父子關系的數組資料轉換成樹形結構
将有父子關系的數組資料轉換成樹形結構

效果圖:

将有父子關系的數組資料轉換成樹形結構