tree 数据结构 已知当前值 把他的所有祖先集都拿到一个数组

20 篇文章 0 订阅
5 篇文章 0 订阅
let currentVal = '1-1-3-2'
    let list = [{
      text: "1省",
      value: "1",
      child: [{
        text: "1市",
        value: "1-1",
        child: [{
            text: "1区",
            value: "1-1-1",
            child: [{
              text: "1区-1镇",
              value: "1-1-1-1",
            }, ],
          },
          {
            text: "2区",
            value: "1-1-2",
            child: [{
              text: "2区-1镇",
              value: "1-1-2-1",
            }, ],
          },
          {
            text: "3县",
            value: "1-1-3",
            child: [{
              text: "3县-1镇",
              value: "1-1-3-1",
            },{
              text: "3县-2镇",
              value: "1-1-3-2",
            } ],
          },
        ],
      }, ],
    }, ];
    // 根据当前位置 区域
    function getDefault(arr, currentVal) {
      let data = JSON.parse(JSON.stringify(arr)) // 对传入的参数进行深拷贝
      let newData = [] // 创建空数组用来接收操作后的新数组
      // 递归 扁平化
      const hasChildren = (item, parentItem = {}) => { // 递归遍历,把包含children的选项拿出来,push到之前新建的空数组内
        item.parentValue = parentItem.value;
        item.child && item.child.length && item.child.forEach(v => {
          hasChildren(v, item)
        })
        delete item.child // 删除原children属性,可选项
        newData.push(item)
      }
      data.forEach(v => hasChildren(v));
      let result = []
      // 通过递归找到对应父级
      const hasParent = (id) => {
        newData.forEach(item => {
          if (id == item.value) {
            result.unshift(item)
            if (item.parentValue) {
              hasParent(item.parentValue)
            }
          }
        })
      }
      hasParent(currentVal)
      return result
    };
    let resultArr = getDefault(list, currentVal)
    console.log('resultArr',resultArr)// [{},{},{},{}]

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值