查找树形数据的某个值
生活随笔
收集整理的這篇文章主要介紹了
查找树形数据的某个值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
很多場景都需要使用樹形數據,比如:一級菜單 - 二級菜單、省-市-區(qū)、公司-部門-小組、界-門-綱-目-科-屬-種 等等。
數據結構通常如下所示(以下代碼為ts寫法):
已知groupId為1-0-0如何找到它對應的名字:西湖區(qū)呢???
思路:
知識點
實現
// 以下代碼有ts報錯,知道怎么解決的請告訴我const findFieldValue = <T>(treeData: T[], key: string, value: string | number, field: string): string | number | boolean | null => {let res: string | number | null = null;const fn = (treeData: T[], key: string, value: string | number, field: K) => {if (!treeData?.length) return key;for (let index = 0; index < treeData.length; index++) {if (treeData[index][key] === value) {res = treeData[index][field];break;}if (treeData[index]?.children?.length) {fn(treeData[index].children, key, value, field);}}};fn(treeData, key, value, field);return res; }結果
cosole.log(findFieldValue(treeData, 'groupId', '1-0-0', 'title')) // 西湖區(qū)總結
以上是生活随笔為你收集整理的查找树形数据的某个值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: solarwinds安装升级NPM和其他
- 下一篇: ISC CCSP 从2022年8月起 支