下面是我们要处理的数据,简写:
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));输出如下图:
这是个很明显的多叉树的树形结构,一般情况下,对于这种树形结构一般采用深度优先遍历和广度优先遍历。
深度优先遍历的原则是: 1. 从顶点开始; 2. 如果当前节点有子节点,则遍历当前节点的所有子节点;
// 递归实现 function deepSearch(tree){ for(var i = 0; i<tree.length; i++) { console.log(tree[i]); if(tree[i].children && tree[i].children.length>0) { deepSearch(tree[i].children); } } } // 非递归 function deepSearch(tree) { var stark = []; stark = stark.concat(tree); while(stark.length) { var temp = stark.shift(); if(temp.children) { // 当前节点有子节点时,将子节点放到当前的栈的前面 stark = temp.children.concat(stark); } console.log(temp); } }广度优先遍历的原则是: 1. 从根节点开始; 2. 遍历所有子节点; 3. 从第一个子节点开始再执行广度优先遍历。 代码如下:
function breadthSearch(tree) { var stark = []; stark = stark.concat(tree); while(stark.length) { var temp = stark.shift(); if(temp.children) { stark = stark.concat(temp.children); } console.log(temp); } }我这里使用的是深度优先