JS遍历树状数据,选择需要的字段重构一个新的树状数据

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)
        })
      }
	}

最终数据
JS遍历树状数据,选择需要的字段重构一个新的树状数据_第1张图片

你可能感兴趣的:(JS)