美文网首页
listToTree

listToTree

作者: believedream | 来源:发表于2018-04-23 19:09 被阅读0次
      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

          本文链接:https://www.haomeiwen.com/subject/twollftx.html