接口返回list数组转换成tree结构

107 阅读1分钟

image.png

        // this.data = res.data;
          // console.log(this.data, "arr");
          // this.data.forEach(element => {
          //   let pid = element.pid;
          //   if (pid != 0) {
          //     this.data.forEach(ele => {
          //       if (ele.id == pid) {
          //         if (!ele.children) {
          //           ele.children = [];
          //         }
          //         ele.children.push(element);
          //       }
          //     });
          //     // console.log(arr); //此时的数组是在原基础上补充了children;
          //     this.data = this.data.filter(ele => ele.pid === 0); //这一步是过滤,按树展开,将多余的数组剔除;
          //     console.log(this.data);
          //     return this.data;
          //   }
          // });
      

image.png

还有一种是插件

       import arrayToTree from "array-to-tree";

      .then(res => {
              this.data = arrayToTree(res.data, {
                parentProperty: "pid",
                customID: "id",
                childrenProperty: "children"
              });