listToTree

  listToTree (data: any[], options: any) {
    if (!isEmpty(data)) {
      options = options || {}
      let ID_KEY: string = options.idKey || 'id'
      let PARENT_KEY: string = options.parentKey || 'parent_id'
      let CHILDREN_KEY: string = options.childrenKey || 'children'
      let PARENT_VAL: number = options.parentVal || 0
      let tree: any[] = []
      let childrenOf: any =  
      let parentId: number
      let item: any
      let id: any
      for (let i: number = 0; i < data.length; i++) {
        item = data[i]
        id = item[ID_KEY]
        parentId = item[PARENT_KEY] || 0
        // 每行数据都可能存在子类
        childrenOf[id] = childrenOf[id] || []
        // 初始化子类
        item[CHILDREN_KEY] = childrenOf[id]
        if (parentId !== PARENT_VAL) {
          // 初始化其父的子节点
          childrenOf[parentId] = childrenOf[parentId] || []
          // 把它推到父类下的children
          childrenOf[parentId].push(item)
        } else {
          tree.push(item)
        }
      }
      return tree
    }
    return []
  }

你可能感兴趣的:(listToTree)