js 实现向树结构添加节点 并 从树结构中获取节点的父级

  • Post author:
  • Post category:其他


  /**
   * 向树结构中添加数据
   *
   * @param object elements 元素信息
   * ps: elements 是元素的element类整个对象
   *
   * @returns bool
   */
  setChildren (elements) {
    let isOk = false
    let catalog = this.elements.treesKV
    var pu = {
      addTree: function (treesData, elements, pid = 'preview') {
        elements.forEach((ele, eleid) => {
          if (ele.pid === pid) {
            let sum = treesData.push({
              id: eleid,
  
              children: []
            })
            // ele.vm.$data.attr['floorCoord'] = sum - 1 // 记录楼层位置下标
            catalog.set(eleid, [sum - 1])
            isOk = true
          } else {
            var pu1 = {
              forT: function (treesData, element, pidCatalog) {
                treesData.forEach((value, index) => {
                  if (value.id === element.pid) {
                    if (value.children.length === 0) {
                      value.children = []
                    }
                    let sum = value.children.push({
                      id: element.id,
                      children: []
                    })

                    pidCatalog.push(sum - 1)
                    catalog.set(element.id, pidCatalog)

                    isOk = true
                  } else {
                    let pidKV = []
                    if (typeof (catalog.get(ele.pid)) !== 'undefined') {
                      pidKV = JSON.parse(JSON.stringify(catalog.get(ele.pid)))
                    }
                    pu1.forT(value.children, element, pidKV)
                  }
                })
              }
            }

            let pidKV = []
            if (typeof (catalog.get(ele.pid)) !== 'undefined') {
              pidKV = JSON.parse(JSON.stringify(catalog.get(ele.pid)))
            }
            pu1.forT(treesData, ele, pidKV)
          }
        })
        return treesData
      }
    }
    // 默认父级id preview
    this.elements.treesData = pu.addTree(this.elements.treesData, elements, 'preview') // 组成树结构
    return isOk
  }



版权声明:本文为wu15010861923原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。