Cascader 级联选择器---遍历获取id的路径

前言

Cascader 级联选择器和Select 选择器不同,级联选择器绑定的是id的路径

例如:

javascript 复制代码
let arr=[
{id:1,label:'班级1',children:[{id:12,label:'学生12'},{id:13,label:'学生13'}]},
{id:2,label:'班级2',children:[{id:14,label:'学生14'}]}
]

Cascader 级联选择器:选中学生13绑定的值为[1,13]

Select 选择器:选中学生13绑定的值为13

因此,如果我们只知道绑定值的情况下,想让Cascader 级联选择器选中对应选项,需要遍历知道路径

遍历获取id的路径

targetId传绑定值,nodes传数组,调用后即可获得id的路径

javascript 复制代码
function findNodePathById(targetId, nodes, path = []) {
  for (const node of nodes) {
    const currentPath = [...path, node.id];
    if (node.id == targetId) {
      return currentPath;
    }
    if (node.children && node.children.length > 0) {
      const found = findNodePathById(targetId, node.children, currentPath);
      if (found.length > 0) {
        return found;
      }
    }
  }
  return [];
}
相关推荐
2401_841495641 天前
【LeetCode刷题】二叉树的中序遍历
数据结构·python·算法·leetcode··递归·遍历
大熊猫侯佩3 天前
星际穿越:SwiftUI 如何让 ForEach 遍历异构数据(Heterogeneous)集合
swiftui·swift·遍历·foreach·any·异构集合·heterogeneous
2401_841495648 天前
【LeetCode刷题】删除链表的倒数第N个结点
数据结构·python·算法·leetcode·链表·遍历·双指针
SunkingYang16 天前
QT中如何遍历QStringList
qt·解析·遍历·方式·读取·qstringlist
SunkingYang16 天前
QT中如何遍历QStringList中的一部分存储到另外一个QStringList
qt·遍历·子集·qstringlist·另一个
Tisfy1 个月前
LeetCode 1351.统计有序矩阵中的负数:O(m+n)时间复杂度——抽象题解
算法·leetcode·矩阵·题解·遍历
Tisfy1 个月前
LeetCode 2483.商店的最少代价:两次遍历 -> 一次遍历
算法·leetcode·题解·遍历
Tisfy1 个月前
LeetCode 955.删列造序 II:模拟(O(mn)) + 提前退出
算法·leetcode·字符串·题解·遍历
2401_841495642 个月前
【LeetCode刷题】合并区间
数据结构·python·算法·leetcode·合并·遍历·排序