Vue把JSON数据做成树结构

在工作中,我们常常会遇到下面的问题,就是把数据转换成树结构来展示或者处理,这个时候就需要对JSON格式的数据进行转化,话不多说,直接上代码。(当一条数据的parentId==另一条数据的id就是他的children)

<script>
export default {
  data() {
    return {
      //树结构数据
      treeData: [],
      //接口获取的数据
      setTree: [],
    };
  },
  methods: {
    //对json的格式的转化
    getListData() {
      let dataArray = [];
      this.setTree.forEach((data) => {
        let parentId = data.parentId;
        if (parentId === 0) {
          let objTemp = {
            id: data.id,
            name: data.name,
            remark: data.remark,
            perms: data.perms,
            parentId: parentId,
            icon: data.icon,
            orderNum: data.orderNum,
            url: data.url,
            type: data.type,
          };
          dataArray.push(objTemp);
        }
      });
      //排序字段
      dataArray.sort((a, b) => a.orderNum - b.orderNum);
      this.treeData = this.data2treeDG(this.setTree, dataArray);
    },
    data2treeDG(datas, dataArray) {
      for (let j = 0; j < dataArray.length; j++) {
        let dataArrayIndex = dataArray[j];
        let childrenArray = [];
        let Id = dataArrayIndex.id;
        for (let i = 0; i < datas.length; i++) {
          let data = datas[i];
          let parentId = data.parentId;
          if (parentId == Id) {
            //判断是否为儿子节点
            let objTemp = {
              id: data.id,
              name: data.name,
              remark: data.remark,
              perms: data.perms,
              parentId: parentId,
              icon: data.icon,
              orderNum: data.orderNum,
              url: data.url,
              type: data.type,
            };
            childrenArray.push(objTemp);
          }
        }
        //排序字段
        childrenArray.sort((a, b) => a.orderNum - b.orderNum);
        dataArrayIndex.children = childrenArray;
        if (childrenArray.length > 0) {
          this.data2treeDG(datas, childrenArray);
        }
      }
      return dataArray;
    },
  },
};
</script>

Logo

前往低代码交流专区

更多推荐