JS递归过滤树形结构数组对象-模糊查询

前言

今天实际项目有个需求,需要由前端来实现简单树形数据的模糊搜索功能,需求是这样的,简单描述下需求内容:

1、父节点含有,将父节点返回(包含所有子节点)

2、父节点没有,但子节点含有,父节点仍要返回,而子节点只返回包含的搜索内容的、

思来想去,最后用了递归 + includes模糊查询 的方式来实现的。特地记录一下

代码实现

js 复制代码
  const filterTree = (tree, val) => {
    let result = []
    tree.forEach(item => {
      if (item.children && item.children.length) {
        let children = filterTree(item.children, val)
        let obj = {
          ...item,
          children
        }
        if (children && children.length) {
          result.push(obj)
        } else if (item.title.includes(val)) {
          result.push({ ...item })
        }
      } else {
        if (item.title.includes(val)) {
          result.push(item)
        }
      }
    })
    return result
  }

测试

js 复制代码
let arr = [
	{
	    title: '你吗?',
	    children: [
	        {
	            title: '很好啊',
	            children: []
	        },
	        {
	            title: '吗',
	            children: [
	                {
	                    title: '好呀',
	                    children: []
	                }
	            ]
	        }
	    ]
	},
	{
	    title: '卡卡卡',
	    children: [
	        {
	            title: '非常好芬',
	            children: []
	        }
	    ]
	},
	{
	    title: '好卡',
	    children: [
	        {
	            title: '非常芬',
	            children: []
	        }
	    ]
	},
	{
	    title: '第三方的好',
	    children: []
	},
	{
	    title: '第三方的',
	    children: [
	        {
	            title: '的',
	            children: [] 
	        }
	    ]
	}
]

filterTree(arr, '好');

运行结果:

相关推荐
蜡笔小柯南33 分钟前
解决:npm install报错,reason: certificate has expired
前端·npm·node.js
lqj_本人2 小时前
鸿蒙OS&UniApp制作多选框与单选框组件#三方框架 #Uniapp
前端·javascript·uni-app
@PHARAOH3 小时前
WHAT - 前端开发流程 SOP(标准操作流程)参考
前端·领导力
松树戈3 小时前
plus-ui&RuoYi-Vue-Plus 基于pgSql本地运行实践
前端·vue.js·spring boot·ui
new6669993 小时前
css画图形
前端·css
Yvonne爱编码4 小时前
CSS- 1.1 css选择器
前端·css·状态模式·html5·hbuilder
SHIPKING3934 小时前
【HTML】个人博客页面
javascript·css·html
山河故人1635 小时前
uniapp使用npm下载
前端·npm·uni-app
-曾牛5 小时前
基于微信小程序的在线聊天功能实现:WebSocket通信实战
前端·后端·websocket·网络协议·微信小程序·小程序·notepad++
一口一个橘子5 小时前
[ctfshow web入门] web72
前端·web安全·网络安全