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 [];
}
相关推荐
Tisfy11 天前
LeetCode 2515.到目标字符串的最短距离:从中间往两边遍历
算法·leetcode·字符串·题解·数组·遍历
Tisfy13 天前
LeetCode 1848.到目标元素的最小距离:数组遍历(附python一行版)
python·leetcode·题解·遍历
Tisfy14 天前
LeetCode 3740.三个相等元素之间的最小距离 I:今日先暴力,“明日“再哈希
算法·leetcode·哈希算法·题解·模拟·遍历·暴力
Tisfy3 个月前
LeetCode 3637.三段式数组 I:一次遍历(三种实现)
算法·leetcode·题解·模拟·数组·遍历·moines
2401_841495643 个月前
【LeetCode刷题】二叉树的中序遍历
数据结构·python·算法·leetcode··递归·遍历
大熊猫侯佩3 个月前
星际穿越:SwiftUI 如何让 ForEach 遍历异构数据(Heterogeneous)集合
swiftui·swift·遍历·foreach·any·异构集合·heterogeneous
2401_841495643 个月前
【LeetCode刷题】删除链表的倒数第N个结点
数据结构·python·算法·leetcode·链表·遍历·双指针
SunkingYang3 个月前
QT中如何遍历QStringList
qt·解析·遍历·方式·读取·qstringlist
SunkingYang3 个月前
QT中如何遍历QStringList中的一部分存储到另外一个QStringList
qt·遍历·子集·qstringlist·另一个