通过最后一级id逐层找到他对应的父级

    // 通过后端返回的最后一级id,找到前面几级的id
    // 通过最后一级id逐层找到他对应的父级
    // 通过这个方法可以得到一个数组,但是是反序的
    findParentId(list, id, result = []) {
      for (let item of list) {
        console.log(`strart=========id是${id}数据是`,JSON.stringify(item))
        if (item.value === id) {
          result.push(id);
          return result;
        }
        if (item.children && item.children.length) {
          const temp = this.findParentId(item.children, id, result);
          if (temp) {
            result.push(item.value);
            return result;
          }
        }
      }
      return null;
    },
list: [
        {
          value: 1,
          label: '1东南2',
          children: [
              {
                value: 2,
                label: '2上海',
                children: [
                  { value: 3, label: '3普陀' },
                ]
              }
          ]
        }
    ]
const res=this.findParentId(this.list,3)
console.log(res.reverse())   //[1,2,3]

正序的

list: [
  {
    value: 4,
    label: '东南'
  },
  {
    value: 1,
    label: '东南',
    children: [
        {
          value: 2,
          label: '上海',
          children: [
            { value: 3, label: '普陀' },
          ]
        },
        {
          value: 7,
          label: '江苏',
          children: [
            { value: 8, label: '南京' },
            { value: 9, label: '苏州' },
          ]
        }
    ]
  }
] 
getParentsById(list, id) {
      for (let i in list) {
          console.log(`strart=========id是${id}和list的${Number(i)+1}条数据,数据是`,JSON.stringify(list[i]))
          if (list[i].value == id) {
              return [list[i].value]
          }
          if (list[i].children) {
              let node = this.getParentsById(list[i].children, id)
              if (node !== undefined) {
                  // 追加父节点
                  node.unshift(list[i].value)
                  return node
              }
          }
      }
    },
      const backRes=[4,3,9]
      let newArr=[]
      backRes.forEach(item=>{
        let res= this.getParentsById(this.list,item)
        newArr.push(res)
      })
      this.value=newArr
      [[4],[1,2,3],[1,7,9]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值