对tree进行添加或删除节点

对树节点进行定义

找到某一个固定的key,添加一个兄弟节点

const treeData = [
            {
                title: 'parent 1',
                key: '0-0',
                children: [
                    {
                        title: 'parent 1-0',
                        key: '0-0-0',
                        disabled: true,
                        children: [
                            {
                                title: 'leaf',
                                key: '0-0-0-0',
                                disableCheckbox: true,
                            },
                            {
                                title: 'leaf',
                                key: '0-0-0-1',
                                children: [
                                    {
                                        title: 'hhh',
                                        key: '0-0-0-1-0',
                                        disableCheckbox: false,
                                    }
                                ]
                            },
                        ],
                    },
                    {
                        title: 'parent 1-1',
                        key: '0-0-1',
                        children: [{ title: 'abc', key: '0-0-1-0' }],
                    },
                ],
            },
        ];

找到某一个固定的key,添加兄弟节点

 const addNode = (treeData, nodeKey) => {
       console.count();
        for (let i = 0; i < treeData.length; i++) {
            if (treeData[i].key === nodeKey) {
                treeData.push({  //treeData[i]的父节点就是treeData
                    title: '新增的节点',
                    key: Math.random() + '',
                })
                break;
            }
            if (treeData[i].children && treeData[i].children.length > 0) {
                addNode(treeData[i].children, nodeKey);
            }
        }
        return treeData;
    };
    
    console.log(addNode(treeData, nodeKey));

找到某一个节点,并删除它。如果children是空数组,删掉children属性

const deleteNode = (treeData, nodeKey) => {
      for (let i = 0; i < treeData.length; i++) {
          if (treeData[i].key === nodeKey) {
              treeData.splice(i, 1);  //会修改原数组
              break;
          }

          const children = treeData[i].children;
          if (children) {
              if(children.length === 0){
                  Reflect.deleteProperty(children, 'children');
              }else{
                  deleteNode(children, nodeKey);
              }
          }
      }
      return treeData;
  }

  console.log(deleteNode(treeData, nodeKey))
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值