
跨级选中节点代码提取
针对省市区结构扁平化提取选中的代码,我们需要进行递归处理。
关键步骤在于传递选中的状态。递归时,如果上层节点选中,则下层所有子节点都视为选中状态。
/**
* 获取所有被选中的代码
* @param {any[]} list 树形结构
* @param {string[]} parentList 到父级所有的代码的数组
* @param {boolean} parentChecked 上级是否被选中,若上级被选中,则下面所有的子选项均是被选中的数据
*/
const getCheckedList = (list, parentList = [], parentChecked = false) => {
let result = [];
list.forEach((item) => {
const checked = parentChecked || item.check; // 父级被选中或当前被选中,均认为是被选中
const codeList = parentList.concat(item.code);
if (item.children) {
// 当前不是最内层
result = result.concat(getCheckedList(item.children, codeList, checked));
} else {
// 已到最内层
if (checked) {
result.push(codeList);
}
}
});
return result;
};使用示例:
console.log(getCheckedList(tree));
以上就是如何通过递归算法提取跨级选中的节点代码?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号