扁平数据树形化

扁平数据树形化

`transformTree(list, options = {}) {
const {
keyField = 'id',
childField = 'children',
parentField = 'parentid'
} = options

  const tree = []
  const record = {}

  for (let i = 0, len = list.length; i < len; i++) {
    const item = list[i]
    const id = item[keyField]

    if (!id) {
      continue
    }

    if (record[id]) {
      item[childField] = record[id]
    } else {
      item[childField] = record[id] = []
    }

    if (item[parentField]) {
      const parentId = item[parentField]

      if (!record[parentId]) {
        record[parentId] = []
      }

      record[parentId].push(item)
    } else {
      tree.push(item)
    }
  }
  return tree
}`
posted @ 2020-04-29 18:02  大耳朵小虎  阅读(208)  评论(0编辑  收藏  举报