JS实现树形结构数据的模糊搜索查询
简单示例:
需求:输入 “题2” 字,希望树形结构中带有 “题2” 字的项显示,即使父节点没有,但子节点含有,父节点仍要返回。
let arr = [ { title: '标题1', children: [ { title: '标题11', children: null }, { title: '标题21', children: null } ] }, { title: '标题2', children: [ { title: '标题22', children: null } ] }, { title: '标题3', children: null } ];
代码实现:
let mapTree = (value, arr) => { let newarr = []; arr.forEach(element => { if (element.title.indexOf(value) > -1) { // 判断条件 newarr.push(element); } else { if (element.children && element.children.length > 0) { let redata = mapTree(value, element.children); if (redata && redata.length > 0) { let obj = { ...element, children: redata }; newarr.push(obj); } } } }); return newarr; }; console.log(mapTree('题2', arr));
结果:
[ { title: '标题1', children: [ { title: '标题21', children: null } ] }, { title: '标题2', children: [ { title: '标题22', children: null } ] } ]
复杂示例:
如果需要匹配多个属性,代码实现如下:
matchTreeData(arr, searchCon) { let newArr = []; let searchNameList = ['name', 'code', 'title']; arr.forEach((item) => { for (let i = 0, len = searchNameList.length; i < len; i++) { let nameKey = searchNameList[i]; if (item.hasOwnProperty(nameKey)) { if (item[nameKey] && item[nameKey].indexOf(searchCon) !== -1) { newArr.push(item); break; } else { if (item.childList && item.childList.length > 0) { let resultArr = this.matchTreeData(item.childList, searchCon); if (resultArr && resultArr.length > 0) { newArr.push({ ...item, childList: resultArr }) break; } } } } else { continue; } } }) return newArr; }
+
(^_^)打赏作者喝个咖啡(^_^)


我要收藏
返回顶部
跳到底部
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2017-09-12 小tips:JS数值之间的转换,JS中最大的Number是多少?,JS == 与 === 的区别
2017-09-12 小tips:JS之浅拷贝与深拷贝
2017-09-12 小tips:JS中typeof与instanceof用法
2017-09-12 小tips:JS严格模式(use strict)下不能使用arguments.callee的替代方案
2017-09-12 小tips:JS中this操作执行像(object.getName = object.getName)()操作改变了this
2015-09-12 CSS让浮动元素水平居中