js converts the data into a tree structure

There are the following data. There is a single piece of data in the array. Each piece of data has a unique ID. The pid represents the parent ID of this piece of data. According to the correspondence between pid and id, a function is implemented to convert the data into a tree structure. data.

var data = [
  {'id':101,'name':'语文','pid': -1},
  {'id':102,'name':'语文知识点1','pid': 101},
  {'id':103,'name':'语文知识点11','pid': 102},
  {'id':104,'name':'语文知识点2','pid': 101},
  {'id':202,'name':'数学知识点1','pid': 201}, 
  {'id':201,'name':'数学','pid': -1},
  {'id':203,'name':'数学知识点2','pid': 201},
  {'id':204,'name':'数学知识点3','pid': 201},
  {'id':302,'name':'英语知识点1','pid': 301}
];

Idea : According to the condition that id is unique, you can first use object or map structure (named obj) to store the data, the key name is id, the value is the corresponding data, and then the current array is traversed, and each item is recorded as list, according to pid , Find the data parentList with the key pid in obj. If the parentList does not exist, it means that the current data is the root node (pid is -1 or there is no matching id), and the list is directly stored in the result array res (initial res is empty [ ]); If it exists, it means that the current data parentList is a parent node data. Check whether it contains the'children' field. If it does, insert the list directly; if not, define parentList['children'] as an empty array and insert the list . Finally res is what you want.

Code:

function toTree(data) {
  let obj = {}, // 使用对象重新存储数据
    res = [], // 存储最后结果
    len = data.length

  // 遍历原始数据data,构造obj数据,键名为id,值为数据
  for (let i = 0; i < len; i++) {
    obj[data[i]['id']] = data[i]
  }

  // 遍历原始数据
  for (let j = 0; j < len; j++) {
    let list = data[j]
    // 通过每条数据的 pid 去obj中查询
    let parentList = obj[list['pid']]

    if (parentList) {
      // 根据 pid 找到的是父节点,list是子节点,
      if (!parentList['children']) {
        parentList['children'] = []
      }
      // 将子节点插入 父节点的 children 字段中
      parentList['children'].push(list)
    } else {
      // pid 找不到对应值,说明是根结点,直接插到根数组中
      res.push(list)
    }
  }

  return res
}

The result after conversion is as follows:

Guess you like

Origin blog.csdn.net/RedaTao/article/details/107932031