The front end converts the data returned from the back end into tree-structured data

demo

Method One Recursion

data

    var data = [
    {
    "area_id": 5,
    "name": "Guangdong Province",
    "parent_id": 0,
    },
    {
    "area_id": 6,
    "name": "Guangzhou City",
    "parent_id": 5,
    },
    {
    "area_id": 7,
    "name": "Shenzhen City",
    "parent_id": 5,
    },
    {
    "area_id": 4,
    "name": "Market",
    "parent_id": 3,
    },
    {
    "area_id": 3,
    "name": "Xie",
    "parent_id": 0,
    },
    {
    "area_id": 2,
    "name": "Test sub-area",
    "parent_id": 1,
    },
    {
    "area_id": 1,
    "name": "Test area",
    "parent_id": 0,
    }
    ]
   function toTreeData(data,pid){
     function tree(id){
       let arr = []
       data.filter(item =>{
          return item.parent_id ==id
       }).forEach(item => {
          arr.push({
            area_id: item.area_id,
            label:item.name,
            children: tree(item.area_id)
          })
       })
       return arr
     }
     return tree(pid)// The parent id of the first level node, null or 0, is passed in as appropriate.
   }


However, this method has a disadvantage. In the data structure I need when I use components, if the child level does not have data, it returns [].
The tree structure that needs to organize data is mainly on menu bar or categorized tree structure, of course, there are subordinate structures such as provinces and cities.

Method 2 - Object

function setTreeData(arr){
    // Delete all children to prevent multiple calls
    arr.forEach(function(item){
        delete item.children
    });
    let map = {};//Building map
    arr.forEach(i=>{
      map[i.area_id]=i; //Construct current data with area_id as key as value
    });
    let treeData = [];
    arr.forEach(child => {
      const mapItem = map[child.parent_id];//Determine whether parent_id of current data exists in map
      if(mapItem){//Existence means that the current data is not the top-level data
      //Note: The data in the map here refers to arr's direction or arr. When the map Item changes, the ARR will also change, stepping on the pit.
        (mapItem.children || (mapItem.children = [])).push(child);//Here we determine whether there is a child in mapItem
      }else {//Non-existent is top-level data
        treeData.push(child)
      }
    })
    return treeData
  }
  console.log(setTreeData(data))

One of the mistakes of this method is that it will change the original data. I have trampled a pit here for a long time, so I initially used the initialization of deleting children.

Reference: A Big Man's

Tags: Javascript

Posted on Sun, 06 Oct 2019 03:15:31 -0700 by Ozzmosis