请教一个js对json遍历的问题

https://img1.mukewang.com/5c0b7eee0001d52403040674.jpg

比如说 我想找得id为4,就应该返回 [1,3,4]
想找得id 为9 该返回 [1,3,9]
想找得id为7 改返回 [6,7]

不知道我说明白没有。谢谢解答啊


HUX布斯
浏览 458回答 1
1回答

开满天机

很多人都在抱怨你没有把代码贴出来,能回答问题的人可都是真心的!简化版实验原始数据(也供其他人可以验证自己的方案)var nodes = [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "id": 1,&nbsp;&nbsp; &nbsp; &nbsp; "children": [&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "id": 3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "children": [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"id": 4},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"id": 9}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "id": 10&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "id": 2&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "id": 6,&nbsp; &nbsp; &nbsp; "children" : [&nbsp; &nbsp; &nbsp; &nbsp; { "id": 5},&nbsp; &nbsp; &nbsp; &nbsp; { "id": 7},&nbsp; &nbsp; &nbsp; &nbsp; { "id": 8}&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }];JS查找输出结果//递归实现//@leafId&nbsp; 为你要查找的id,//@nodes&nbsp; &nbsp;为原始Json数据//@path&nbsp; &nbsp; 供递归使用,不要赋值function findPathByLeafId(leafId, nodes, path) {&nbsp; if(path === undefined) {&nbsp; &nbsp; path = [];&nbsp; }&nbsp; for(var i = 0; i < nodes.length; i++) {&nbsp; &nbsp; &nbsp; var tmpPath = path.concat();&nbsp; &nbsp; &nbsp; tmpPath.push(nodes[i].id);&nbsp; &nbsp; &nbsp; if(leafId == nodes[i].id) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return tmpPath;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if(nodes[i].children) {&nbsp; &nbsp; &nbsp; &nbsp; var findResult = findPathByLeafId(leafId, nodes[i].children, tmpPath);&nbsp; &nbsp; &nbsp; &nbsp; if(findResult) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return findResult;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; }}//用法console.log(findPathByLeafId(4, nodes));&nbsp; &nbsp;//输出 [1,3,4]console.log(findPathByLeafId(9, nodes));&nbsp; &nbsp;//输出 [1,3,9]console.log(findPathByLeafId(7, nodes));&nbsp; &nbsp;//输出 [6,7]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript