js 处理数组层级化

实例:实现Ant Design Vue的级联选择
在这里插入图片描述
层级数据:有父子关系的数组,且子节点都会放到该节点的children下。

<a-cascader
   :options="options"
 />
data() {
  return {
    options: [],
  };
},
created() {
  this.getData();
},
methods: {
  getData() {
    const data = [
      {
        "id":"60404a146fe3ff06ff74e06b",
        "name":"Test 22",
        "parentId":"",
      },
      {
        "id":"60404a006fe3ff06fb4436c6",
        "name":"Test 11",
        "parentId":"",
      },
      {
        "id":"604045f6b2fc301fde55f8c2",
        "name":"Test 4",
        "parentId":"604045dfb2fc30196037f916",

      },
      {
        "id":"604045f4b2fc301fb804d3d3",
        "name":"三级分类1-3-2",
        "parentId":"604045e0b2fc30191e192645",
      },
      {
        "id":"604045f1b2fc301fa207d323",
        "name":"三级分类1-3-1",
        "parentId":"604045e0b2fc30191e192645",
      },
      {
        "id":"604045e0b2fc30191e192645",
        "name":"二级分类1-3",
        "parentId":"6040459bb2fc3019011a8ee5",
      },
      {
        "id":"604045dfb2fc30196037f916",
        "name":"Test 3",
        "parentId":"604045cfb2fc30190862523b",
      },
      {
        "id":"604045dcb2fc3018fc2569a7",
        "name":"二级分类1-2",
        "parentId":"6040459bb2fc3019011a8ee5",
      },
      {
        "id":"604045d7b2fc3019364c2dd5",
        "name":"二级分类1-1",
        "parentId":"6040459bb2fc3019011a8ee5",
      },
      {
        "id":"604045cfb2fc30190862523b",
        "name":"Test 2",
        "parentId":"604045bfb2fc30196037f915",
      },
      {
        "id":"604045bfb2fc30196037f915",
        "name":"Cynthia Test",
        "parentId":"",
      },
      {
        "id":"604045a5b2fc301908625236",
        "name":"一级分类3",
        "parentId":"",
      },
      {
        "id":"604045a0b2fc30191d3cd524",
        "name":"一级分类2",
        "parentId":"",
      },
      {
        "id":"6040459bb2fc3019011a8ee5",
        "name":"一级分类1",
        "parentId":"",
      }
    ];

    data.forEach((item) => {
      const { id, name } = item;
      item.value = id;
      item.label = name;
    });
    this.classificationOptions = this.treeData(data);
  },
  treeData(data) {
    const cloneData = JSON.parse(JSON.stringify(data));
    return cloneData.filter((father) => {
      const branchArr = cloneData.filter((child) => father.id === child.parentId);
      if (branchArr.length > 0) {
        father.children = branchArr;
      }
      return father.parentId === '';  //返回第一层
    });
  },
},

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值