递归对树形结构数据处理---js模糊查询

下面是我们要处理的数据,简写:

	let arr = [
		{
			title: '你好吗?',
			children: [
				{
					title: '很好啊',
					children: null
				},
				{
					title: '是吗',
					children: null
				}
			]
		},
		{
			title: '卡卡卡',
			children: [
				{
					title: '非常好芬',
					children: null
				}
			]
		},
		{
			title: '第三方的',
			children: null
		}
	];

再搜索框输入 好 字时,希望树形结构中带有 好 字的项显示,即使父节点没有 好 字,但子节点含有,父节点仍要返回;代码实现如下:

const rebuildData=(value, arr) => {
  	let newarr = [];
  	arr.forEach(element => {
    if (element.children && element.children.length) {
      const ab = rebuildData(value,element.children);
      const obj = {
        ...element,
        children: ab
      };
      if (ab && ab.length) {
        newarr.push(obj);
      }
    } else {
      if (element.title.indexOf(value) > -1) {
        newarr.push(element);
      }
    }
  });
  return newarr;
};
	console.log(rebuildData( '好', arr));

输出如下图:
在这里插入图片描述
根据大家提的无法搜索父节点进行了优化:

const rebuildData = (value, arr) => {
      let newarr = [];
      arr.forEach(element => {
        if (element.title.indexOf(value) > -1) {
          newarr.push(element);
        } else {
          if (element.children && element.children.length > 0) {
            const ab = rebuildData(value, element.children);
            const obj = {
              ...element,
              children: ab
            };
            if (ab && ab.length>0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    };

根据大家在评论里提的匹配到父节点,children全部匹配到bug进行优化,最终版:

const rebuildData = (value, arr) => {
      if (!arr) {
        return []
      }
      let newarr = [];
      arr.forEach(element => {
        if (element.title.indexOf(value) > -1) {
          const ab = rebuildData(value, element.children);
          const obj = {
            ...element,
            children: ab
          }
          newarr.push(obj);
        } else {
          if (element.children && element.children.length > 0) {
            const ab = rebuildData(value, element.children);
            const obj = {
              ...element,
              children: ab
            };
            if (ab && ab.length > 0) {
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    };
    
console.log(rebuildData('好', arr));
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值