antd Tree 处理数据根据末端子元素的状态改变所有父元素的状态

拿到树结构的数据

let a = [
{

key: 1,
title: '一级',
parentKey: 0,
checked: true,
children: [
  {
    key: 10, title: '一级-0', parentKey: 1, checked: true, children: [
      {key: 15, title: '一级-0-1', parentKey: 10, checked: false},
      {key: 16, title: '一级-0-2', parentKey: 10, checked: true}
    ]
  },
  {key: 11, title: '一级-1', parentKey: 1, checked: false},
  {key: 12, title: '一级-2', parentKey: 1, checked: false},
  {key: 13, title: '一级-3', parentKey: 1, checked: false},
  {key: 14, title: '一级-4', parentKey: 1, checked: false}
]
}
];

 逻辑:当这个'一级-0-1'这里这条数据为false时,那么他的父级也就是'一级-0''一级',这两个父级也应该是false。如果层级少的话还简单,循环两次但是如果层级到了五六层就比较麻烦了。

废话不说上代码:

  const transformTree = (list: any, arr: []) => {
    list.filter(x => {
      if (x.children.length === 0) {
        return arr.push(x)
      } else {
        const flag = chooseCheck([x.children])
        const obj = {
          checked: flag,
          children: [],
          key: x.key,
          title: x.title,
          parentKey: x.parentKey
        }
        arr.push(obj)
        transformTree(x.children, arr)
      }
    })
    return arr
  }
  const chooseCheck = list => {
    let choosed = false
    ;(list || []).forEach(data => {
      if (data.children && data.children.length > 0) data.checked = chooseCheck(data.children)
      if (data.checked) choosed = true
    })

    return choosed
  }

菜鸟代码,大佬多多指点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值