由于最近做级联选择,有这个需求,闲着没事就搞了一下。代码非最优,不喜勿喷。
- 数据
[
{ id: 1, label: '第一项', value: 'f1' },
{
id: 2,
label: '第二项',
value: 'f2',
children: [
{ id: 3, label: '第2-1项', value: 'f21' },
{ id: 4, label: '第2-2项', value: 'f22', children: undefined },
],
},
];
- 类型
interface SelectItem {
id?: string | number;
label?: string;
value?: string;
children?: SelectItem[];
}
- 深度函数
// 遍历任意树深度
public getDepth(options: SelectItem[]) {
let arr: SelectItem[] = JSON.parse(JSON.stringify(options));
let depth = 0;
while (arr.length > 0) {
depth++;
const temp = arr;
// 遍历当前深度所有节点
arr = [];
temp.forEach((t) => {
t.children?.forEach((ot) => { arr.push(ot); });
});
}
return depth;
}

被折叠的 条评论
为什么被折叠?



