javascript - Ask a question about js to json traversal
淡淡烟草味
淡淡烟草味 2017-05-19 10:35:55
0
4
451


For example, if I want to find an id of 4, I should return [1,3,4]
If I want to find an id of 9, I should return [1,3 ,9]
The id you want to find is 7, change it to return [6,7]

I don’t know if I made it clear. Thanks for the answer

淡淡烟草味
淡淡烟草味

reply all(4)
大家讲道理

Many people are complaining that you didn’t post the code, but those who can answer the questions are sincere!
Simplified version of the original experimental data (also for others to verify their own solutions)

var nodes = [
    {
      "id": 1, 
      "children": [
        {
          "id": 3,
          "children": [
            {"id": 4},
            {"id": 9}
          ]
        },
        {
          "id": 10
        },
      ]
    },
    {
      "id": 2
    },
    {
      "id": 6,
      "children" : [
        { "id": 5},
        { "id": 7},
        { "id": 8}
      ]
    }
];

JS search output results

//递归实现
//@leafId  为你要查找的id,
//@nodes   为原始Json数据
//@path    供递归使用,不要赋值
function findPathByLeafId(leafId, nodes, path) {
  if(path === undefined) {
    path = [];
  }
  for(var i = 0; i < nodes.length; i++) {
      var tmpPath = path.concat();
      tmpPath.push(nodes[i].id);
      if(leafId == nodes[i].id) {
         return tmpPath;
      }
      if(nodes[i].children) {
        var findResult = findPathByLeafId(leafId, nodes[i].children, tmpPath);
        if(findResult) {
          return findResult;
        }
      }
  }
}

//用法
console.log(findPathByLeafId(4, nodes));   //输出 [1,3,4]
console.log(findPathByLeafId(9, nodes));   //输出 [1,3,9]
console.log(findPathByLeafId(7, nodes));   //输出 [6,7]
滿天的星座

Can you post the code... It's hard to process a picture like this...

巴扎黑

Direct recursive traversal, first check whether the ids are the same, return directly if they are the same, if they are different, check whether there are children. If there are children, record the id of the current layer and continue to traverse downwards. If not, clear the record and skip the current node and traverse The next node at the same level.

给我你的怀抱
function solution(arr,id){
var ans=[];
var flag=false;
function dps(obj,depth){
    ans[depth]=obj.id;
    if(obj.id==id){
        flag = true;
    }else{
        if(obj.children)
        for(var i=0;i<obj.children.length;i++){
            flag = dps(obj.children[i],depth+1);
            if(flag)
                break;
        }
    }
    if(flag)
        return flag;
    ans[depth]=undefined;
}
arr.forEach(function(a){if(dps(a,0))return;})
return ans.filter(function(obj){return undefined!=obj;});
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template