1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
| let treeList = [ { id: '1', name: '父一', children: [ { id: '1-1', name: '子一一', children: [ { id: '1-1-1', name: '孙一一', children: null }, { id: '1-1-2', name: '孙一二', children: null }, { id: '1-1-3', name: '孙一三', children: null } ] } ] }, { id: '2', name: '父二', children: [ { id: '2-1', name: '子二一', children: null }, { id: '2-2', name: '子二一', children: null }, { id: '2-3', name: '子二一', children: null } ] }, { id: '3', name: '父三', children: null } ] 01.根据id查询id所对应的对象
function getObjById(list,id){ //判断list是否是数组 if(!list instanceof Array){ return null } //遍历数组 for(let i in list){ let item=list[i] //此处的值可修改为与自己数组所匹配的值 if(item.id===id) { return item }else{ //查不到继续遍历 if(item.children){ let value=getObjById(item.children,id) //查询到直接返回 if(value){ return value } } } } } //测试 console.log(getObjById(treeList,"1-1-3")) 结果: { id: '1-1-3', name: '孙一三', children: null }
2.根据id查询本节点和所有父级节点 function getParentsById(list,id){ for (let i in list) { if (list[i].id === id) { //查询到就返回该数组对象 return [list[i]] } if (list[i].children) { let node = getParentsById(list[i].children, id) if (node !== undefined) { //查询到把父节点连起来 return node.concat(list[i]) } } } } console.log(getParentsById(treeList,'2-3')) 结果: [{id: "2-3", name: "子二一", children: null}, {id: "2", name: "父二", children: Array(3)}]
3.根据id查询该节点和所有子节点
//需要用到上面的根据id查询该节点对象 function getObjById(list,id){ //判断list是否是数组 if(!list instanceof Array){ return null } //遍历数组 for(let i in list){ let item=list[i] //此处的值可修改为与自己数组所匹配的值 if(item.id===id) { return item }else{ //查不到继续遍历 if(item.children){ let value=getObjById(item.children,id) //查询到直接返回 if(value){ return value } } } } } // list 为已查询到的节点children数组,returnvalue为返回值(不必填) function getChildren (list,returnValue=[]) { for(let i in list){ //把元素都存入returnValue returnValue.push(list[i]) if (list[i].children) { getChildren(list[i].children, returnValue) } } return returnValue } //age: let obj=getObjById(treeList,"1") if(obj&&obj.children){ let childrenList=getChildren(obj.children) console.log(childrenList) } else { console.log("没有该节点或者没有子元素") }
结果为:[ {id: "1-1", name: "子一一", children: Array(3)},
{id: "1-1-1", name: "孙一一", children: null},
{id: "1-1-2", name: "孙一二", children: null},
{id: "1-1-3", name: "孙一三", children: null}]
|