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, '好');

运行结果:

相关推荐
anOnion1 天前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
用户47949283569151 天前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端
JieE2121 天前
LeetCode 101. 对称二叉树|JS 递归 + 迭代双解法,彻底搞懂镜像判断
javascript·算法
冬奇Lab1 天前
AI Workflow 定义的四次演进:从 Markdown 到 JS 脚本,再到分布式多 Agent
javascript·人工智能·agent
zhangxingchao1 天前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒1 天前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic1 天前
SwiftUI 手势笔记
前端·后端
橙子家1 天前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518131 天前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州1 天前
CSS aspect-ratio 属性完全指南
前端