Cascader 级联选择器--扁平对象数组转换成级联选择器所需要的树形结构数据

1.例:从后端接口中获得的扁平数据

let treeList = [
	{
		id: 1,
		name: '一年级',
		parentId: 0,
		parentName: '学校'
	},
	{
		id: 2,
		name: '二年级',
		parentId: 0,
		parentName: '学校'
	},
	{
		id: 3,
		name: '一年级一班',
		parentId: 1,
		parentName: '一年级'
	},
	{
		id: 4,
		name: '一年级一班第一小组',
		parentId: 3,
		parentName: '一年级一班'
	},
]

2.数组转为树形结构

// 数组转为树形结构
    arrayToTree (items) {
      const result = [];   // 存放结果集
      const itemMap = {};
      for (const item of items) {
          const id = item.id;
          const pid = item.parentId;

          if (!itemMap[id]) {
              itemMap[id] = {
                  children: [],
              }
          }

          itemMap[id] = {
            ...item,
            children: itemMap[id]['children']
          }

          const treeItem = itemMap[id];

          if (pid === 0) {
              result.push(treeItem);
          } else {
            if (!itemMap[pid]) {
                itemMap[pid] = {
                    children: [],
                }
            }
            itemMap[pid].children.push(treeItem);
          }

      }
      return result;
    },

3.上面处理完后我们会发现最后一级叶子节点有一个空的children空属性,在实际级联选择器中会显示无数据,所以需要对这一问题进行处理

// 处理叶子节点
    isChildrenNull(arr) {
      return arr.map(item => {
          if (item.children.length > 0) {
            this.isChildrenNull(item.children)
          } else {
            delete item.children
          }
          return item;
      })
    },

饿了么官方文档

4.同时我们注意到官方文档中的需要的是value和label,但是我们拿到的数据是id和name,所以我们还需修改节点属性的名称

// 修改属性名称,构造级联选择器数据结构
    changeObjaryKey(objAry, key, newkey) {
      objAry.forEach(item => {
        // 新增替换的属性的键值
        Object.assign(item, {
          [newkey]: item[key]
        })
        // 去掉旧属性键值
        delete item[key]
        this.changeObjaryKey(item.children, key, newkey)
      });
    },

5.代码调用示例如下:

<el-cascader
 v-model="addForm.parentCpId"
  :options="optionList"
  :show-all-levels="false"
  placeholder="请选择"
  style="width: 2.6rem">
</el-cascader>

let optionList = this.arrayToTree(treeList);
this.changeObjaryKey(optionList, 'id', 'value');
this.changeObjaryKey(optionList, 'name', 'label');
this.isChildrenNull(optionList);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值