How to convert tiled data into tree form?

way1: recursive implementation

Ideas:

(1) First loop through to find the first-level data, and put the data into the new array

(2) Call the function again to loop, find out the second-level data and make a judgment

         If there is second-level data, add the second-level data to the children corresponding to the first-level data

 const arr = [
      { id: '01', name: '张三', school: '清华', pid: '' },
      { id: '02', name: '李四', school: '北大', pid: '01' },
      { id: '03', name: '王五', school: '上外', pid: '01' },
      { id: '04', name: '赵六', school: '上交', pid: '' },
      { id: '05', name: '孙七', school: '武大', pid: '04' },
      { id: '06', name: '周八', school: '人大', pid: '04' },
      { id: '07', name: '吴九', school: '交大', pid: '04' },
    ]
    // 递归-平铺数据转树形
    function transDataToTree (arr, pid = '') {

      const newArr = []

      arr.map(item => {

        // 找出第一级
        if (item.pid === pid) {
          newArr.push(item)

          // 找出第二级
          const children = transDataToTree(arr, item.id)
          // 如果有第二级的数据,就加到第一级的children里面,没有就不加
          if (children.length > 0) {
            item.children = children
          }
        }
        return newArr
      });
      return newArr
    }
    console.log(transDataToTree(arr), newArr);

way2: array forEach method

Ideas:

(1) Traverse the original array

      Add a children to each item of data

      Generate a new array object obj: each object in it takes id as the attribute name and item as the attribute value

(2) Traverse the original array again for judgment

      If the item has a pid, add the item to the item.children of the corresponding superior

      If there is no superior element, put it directly into the array and return it

const arr = [
      { id: '01', name: '张三', school: '清华', pid: '' },
      { id: '02', name: '李四', school: '北大', pid: '01' },
      { id: '03', name: '王五', school: '上外', pid: '01' },
      { id: '04', name: '赵六', school: '上交', pid: '' },
      { id: '05', name: '孙七', school: '武大', pid: '04' },
      { id: '06', name: '周八', school: '人大', pid: '04' },
      { id: '07', name: '吴九', school: '交大', pid: '04' },
    ]

    function tranDataToTree (arr) {

     // 定义变量 接收要收到的数据
      const treeArr = []
      const obj = {}

     // 遍历数组: 给每一项加一个children + 生成新obj
      arr.forEach(item => {
        item.children = []
        obj[item.id] = item
      })

     // 再次循环数组, 如果每一个元素item有上级元素pid,就把item添加到对应上级的item.children里
     // 如果没有上级元素,就直接放进treeArr里面
      arr.forEach(item => {
        if (obj[item.pid]) {
          obj[item.pid].children.push(item)
        } else {
          treeArr.push(item)
        }
      })
      return treeArr
    }

    console.log(transDataToTree(arr), newArr);

Guess you like

Origin blog.csdn.net/weixin_48082900/article/details/128547607