递归寻找树结构的子节点
<script> let treeData = [{ id:'1', children:[{ id:'11', children:[{ id:'111' },{ id:'112' }] },{ id:'12', children:[{ id:'122' }] }] },{ id:'2', children:[{ id:'21', children:[{ id:'211' },{ id:'212' }] },{ id:'22', children:[{ id:'221' },{ id:'222' }] }] },{ id:'3', children:[{ id:'31', children:[{ id:'311' },{ id:'312' },{ id:'313' }] },{ id:'32', children:[{ id:'321' },{ id:'322' },{ id:'323' }] }] }] let result = [1,12,213,222] let fn1 = function(ids,data){ if(data.id == ids){ return data; } if(data.children&&data.children.length != 0){ for(let i =0;i<data.children.length;i++){ let res = fn1(ids,data.children[i]); if(res && res.id == ids){ return res; } } } return null; } let fn= function(ids,data){ let res; for(let i=0;i<data.length;i++){ res=fn1(ids,data[i]); if(res && res.id == ids){ //判读是否是子节点,否的话返回null if(res.children&&res.children.length != 0){ res = null; } break; } } return res } result.forEach(item =>{ console.log(fn(item,treeData)) }) </script>
打印结果
多多关照,多多指教,共同成长
---嘉煠