JS原生实现TreeSelect取消方法

1 篇文章 0 订阅
该代码实现了一个名为handleUnCheck的函数,用于在树形数据结构中取消选中指定节点及其所有子节点,并更新已选中的键列表。它首先将树数据扁平化,然后遍历扁平化后的数据来取消选中相关节点及其父节点。此功能适用于具有层级关系的数据管理场景。
摘要由CSDN通过智能技术生成
 const TREE_DATA = [
    {
      key: "a-1",
      children: [
        {
          key: "b-1",
          children: [
            { key: "c-1-1" },
            {
              key: "c-1-2",
              children: [
                {
                  key: "d-1-2-1",
                }
              ]
            }
          ],
        },
        { key: "b-2" },
        { key: "b-3" },
      ],
    },
    { key: "a-2" },

  ];

  const handleUnCheck = (treeData, perCheckedKedys, key) => {
    const treeFormat = (tree, initFlatTree = [], parentKey = "") => {
      const cacheTree = [...initFlatTree];
      tree.forEach((item) => {
        cacheTree.push({
          parentKey,
          key: item.key,
          children: (item?.children || []).map((v) => v.key),
        });

        if (item?.children?.length) {
          cacheTree.push(...treeFormat(item?.children, cacheTree, item.key));
        }
      });
      return cacheTree;
    };

    const flatTree = treeFormat(treeData);

    let newPerCheckedKedys = [...perCheckedKedys];
    // 取消current
    newPerCheckedKedys = newPerCheckedKedys.filter((item) => item !== key);

    const current = flatTree.find((item) => item.key === key) || {};
    // 取消children
    const onCancelChildren = (children = []) => {
      if (children.length) {
        children.forEach((childKey) => {
          newPerCheckedKedys = newPerCheckedKedys.filter(
            (item) => item !== childKey
          );
          const child = flatTree.find((item) => item.key === childKey);
          onCancelChildren(child?.children);
        });
      }
    };
    onCancelChildren(current?.children || []);

    // 取消parents
    const onCancelParents = (parentKey = "") => {
      if (!parentKey) return;
      const parent = flatTree.find((item) => item.key === parentKey);
      if (parent) {
        let flag = false;
        parent.children.forEach((childKey) => {
          if (newPerCheckedKedys.includes(childKey)) {
            flag = true;
          }
        });
        if (!flag) {
          newPerCheckedKedys = newPerCheckedKedys.filter(
            (item) => item !== parentKey
          );
          onCancelParents(parent.parentKey);
        }
      }
    };

    onCancelParents(current.parentKey);
    return newPerCheckedKedys
  };

  // handleUnCheck(TREE_DATA, ["a-1", "b-1", "c-1-1"], "c-1-1");
  // handleUnCheck(TREE_DATA, ["a-1", "b-1", "b-2", "c-1-1"], "c-1-1");
  const keys = handleUnCheck(TREE_DATA, ["a-1", "b-1", "c-1-2", 'd-1-2-1', "a-2"], "c-1-2");
  console.log(keys)//['a-2']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值