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']
JS原生实现TreeSelect取消方法
最新推荐文章于 2024-07-16 01:39:52 发布
该代码实现了一个名为handleUnCheck的函数,用于在树形数据结构中取消选中指定节点及其所有子节点,并更新已选中的键列表。它首先将树数据扁平化,然后遍历扁平化后的数据来取消选中相关节点及其父节点。此功能适用于具有层级关系的数据管理场景。
摘要由CSDN通过智能技术生成