JS遍歷樹狀資料,選擇需要的欄位重構一個新的樹狀資料

幾度風雨見丹心發表於2020-10-10

1、原樹狀結構資料

treeData = [
      {
        "id": 1,
        "parentId": 0,
        "type": "結生上取段日名求將查由六才酸商驗又每。",
        "referenceId": 234,
        "sort": 29,
        "code": "你計世派列太是後氣住內帶卻所就。",
        "name": "直按種白親叫也總較機低及省。",
        "userCount": 196,
        "description": "空價等名共通七鬥海共度實養族識觀東。",
        "modifyDate": null,
        "makeBillMan": "test",
        "createDate": null,
        "modifier": "test",
        "deleteFlag": false,
        "children": [
          {
            "id": 2,
            "parentId": 1,
            "type": "結生上取段日名求將查由六才酸商驗又每。",
            "referenceId": 234,
            "sort": 29,
            "code": "你計世派列太是後氣住內帶卻所就。",
            "name": "直按種白親叫也總較機低及省。",
            "userCount": 196,
            "description": "空價等名共通七鬥海共度實養族識觀東。",
            "modifyDate": null,
            "makeBillMan": "test",
            "createDate": null,
            "modifier": "test",
            "deleteFlag": false,
            "children": [
              {
                "id": 3,
                "parentId": 2,
                "type": "結生上取段日名求將查由六才酸商驗又每。",
                "referenceId": 234,
                "sort": 29,
                "code": "你計世派列太是後氣住內帶卻所就。",
                "name": "直按種白親叫也總較機低及省。",
                "userCount": 196,
                "description": "空價等名共通七鬥海共度實養族識觀東。",
                "modifyDate": null,
                "makeBillMan": "test",
                "createDate": null,
                "modifier": "test",
                "deleteFlag": false,
                "children": []
              }
            ]
          }
        ]
      }

要求:新建的陣列要有和源資料一樣的結構,其中只保留label=name,和children欄位,children陣列為空時去掉children欄位。

	data() {
      return {
        treeData: null,
        newTreeList: []
      }
    },
    created() {
      this.getTreeList([this.treeData],this.newTreeList);
    },
    methods:{
	  // 遞迴樹狀資料
      getTreeList(treeList,newTreeList) {
        treeList.map(c=>{
          let tempData={
            label:c.name
          }
          if(c.children && c.children.length>0){
            tempData.children=[]
            this.getTreeList(c.children,tempData.children)
          }
          newTreeList.push(tempData)
        })
      }
	}

最終資料
在這裡插入圖片描述

相關文章