简单示例:
需求:输入 “题2” 字,希望树形结构中带有 “题2” 字的项显示,即使父节点没有,但子节点含有,父节点仍要返回。
let arr = [ { title: '标题1', children: [ { title: '标题11', children: null }, { title: '标题21', children: null } ] }, { title: '标题2', children: [ { title: '标题22', children: null } ] }, { title: '标题3', children: null } ];
代码实现:
let mapTree = (value, arr) => { let newarr = []; arr.forEach(element => { if (element.title.indexOf(value) > -1) { // 判断条件 newarr.push(element); } else { if (element.children && element.children.length > 0) { let redata = mapTree(value, element.children); if (redata && redata.length > 0) { let obj = { ...element, children: redata }; newarr.push(obj); } } } }); return newarr; }; console.log(mapTree('题2', arr));
结果:
[ { title: '标题1', children: [ { title: '标题21', children: null } ] }, { title: '标题2', children: [ { title: '标题22', children: null } ] } ]
复杂示例:
如果需要匹配多个属性,代码实现如下:
matchTreeData(arr, searchCon) { let newArr = []; let searchNameList = ['name', 'code', 'title']; arr.forEach((item) => { for (let i = 0, len = searchNameList.length; i < len; i++) { let nameKey = searchNameList[i]; if (item.hasOwnProperty(nameKey)) { if (item[nameKey] && item[nameKey].indexOf(searchCon) !== -1) { newArr.push(item); break; } else { if (item.childList && item.childList.length > 0) { let resultArr = this.matchTreeData(item.childList, searchCon); if (resultArr && resultArr.length > 0) { newArr.push({ ...item, childList: resultArr }) break; } } } } else { continue; } } }) return newArr; }