树形数据转json

数据格式
  分享图片

 

返回数据格式1: (最后一级children如果为空,则为children:[])

    transData(data) {
      const resData = data
      const tree = []
      for (let i = 0; i < resData.length; i++) {
        if (resData[i][‘domainLevel‘] === ‘1‘) {
          const obj = {
            domainCode: resData[i][‘domainCode‘],
            domainDescription: resData[i][‘domainDescription‘],
            domainLevel: resData[i][‘domainLevel‘],
            children:[]
          }
          tree.push(obj)
          resData.splice(i, 1)
          i--
        }
      }
      this.run(tree, resData)

 

      return tree
    },
    run(chiArr, resData) {      
        if (resData && resData.length !== 0) {
        for (let i = 0; i < chiArr.length; i++) {
          for (let j = 0; j < resData.length; j++) {
            if (resData[j][‘domainCode‘].substring(0, chiArr[i].domainCode.length) === chiArr[i].domainCode && resData[j][‘domainLevel‘] === (parseInt(chiArr[i].domainLevel) + 1).toString()) {
              const obj = {
                domainCode: resData[j][‘domainCode‘],
                domainDescription: resData[j][‘domainDescription‘],
                domainLevel: resData[j][‘domainLevel‘],
                children: []
              }
              chiArr[i].children.push(obj)
              resData.splice(j, 1)
              j--
            }
          }
          this.run(chiArr[i].children, resData)
        }
      }
    }
 
返回格式2:(最后一级children如果为空,则不要children)

    transData(data) {
      const resData = data
      const tree = []
      for (let i = 0; i < resData.length; i++) {
        if (resData[i][‘domainLevel‘] === ‘1‘) {
          const obj = {
            domainCode: resData[i][‘domainCode‘],
            domainDescription: resData[i][‘domainDescription‘],
            domainLevel: resData[i][‘domainLevel‘]
          }
          tree.push(obj)
          resData.splice(i, 1)
          i--
        }
      }
      this.run(tree, resData)

      return tree
    },
    run(chiArr, resData) {
      for (let i = 0; i < chiArr.length; i++) {
        const temp = resData.filter(item => item.domainCode.substring(0, chiArr[i].domainCode.length) === chiArr[i].domainCode && item.domainLevel === (parseInt(chiArr[i].domainLevel) + 1).toString())
        if (temp && temp.length > 0) {
          chiArr[i].children = temp
        }
        if (chiArr[i].children) {
          this.run(chiArr[i].children, resData)
        }
      }
    },
相关文章
相关标签/搜索