数组转换树形结构,向上取所有父节点,向下取所有自己点

    数组转化成树形结构
    gettree(data) {
      var dataList = data
      function fn(data, sjdxid) {
        var result = []
        var temp
        for (var i in data) {
          if (data[i].sjdxid === sjdxid) {
            result.push(data[i])
            temp = fn(data, data[i].dxid)
            if (temp.length > 0) {
              data[i].children = temp
            }
          }
        }
        return result
      }
      return fn(dataList, undefined)
    },
    
    当前节点找所有父节点
    findPar(array, label) {
      var stack = []
      var going = true
      function getPar(array, label) {
        array.forEach(item => {
          if (!going) return
          stack.push(item)
          if (item.dxid === label) {
            going = false
          } else if (item.children) {
            getPar(item.children, label)
          } else {
            stack.pop()
          }
        })
        if (going) stack.pop()
      }
      getPar(array, label)
      return stack
    },


    当前节点找所有自己点传的是原始数组
    findChild(array, id) {
      var newArray = []
      var orginization = array
      function getchild(id) {
        for (var i = 0; i < orginization.length; i++) {
          if (orginization[i].sjdxid === id) {
            newArray.push(orginization[i])
            getchild(orginization[i].dxid)
          } else {
            continue
          }
        }
        return newArray
      }
      return getchild(id)
    }

 

你可能感兴趣的:(js)