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

1,558 阅读1分钟

前言

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

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

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

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

代码实现

  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
  }

测试

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

运行结果:

image.png