javascript树与每个节点的路径

时间:2016-09-11 22:10:26

标签: javascript tree

我正在尝试用每个节点的路径创建一个树:

Plunkr实际演示(仅参见控制台):https://plnkr.co/edit/peCIZcSzChF3b2WnaOxk?p=preview

原始数据: (这是标签列表,“父”是父ID)

var originals=[
    {"id":1,"name":"Grammaire","parent":null},
    {"id":2,"name":"Orthographe","parent":null},
    {"id":8,"name":"Orthographe lexicale","parent":2},
    {"id":9,"name":"Orthographe grammaticale","parent":2},
    {"id":10,"name":"Adjectif couleur","parent":9},
    {"id":11,"name":"Nombre","parent":8},
    {"id":12,"name":"Annalyse grammaticale","parent":1},
    {"id":19,"name":"Concordance des temps","parent":1},
    {"id":20,"name":"annalyse 2","parent":12}
];

所以应该制作一个这样的树:

1-Grammaire
  12-Annalyse grammaticale
    20-Annalyse 2
  19-Concordance des temps
2-Orthographe
  8-Orthographe lexicale
  9-Orthographe grammaticale
    10-Adjectif couleur
    11-Nombre

我得到了一个代码:

 function convert(array){
      var map = {};
      for(var i = 0; i < array.length; i++){
            var obj = array[i];
            obj["children"] = [];
            map[obj.id] = obj;
            var parent = obj.parent || '-';
            if(!map[parent]){
                 map[parent] = {
                      children: []
                 };
            }       
            map[parent].children.push(obj);
      }
      return map['-'].children;
 }

结果:

[
    {"id":1,"name":"Grammaire","parent":null,
        "children":[
            {"id":12,"name":"Annalyse grammaticale","parent":1,
                "children":[{"id":20,"name":"annalyse 2","parent":12,"children":[]}]
            },
            {"id":19,"name":"Concordance des temps","parent":1,"children":[]}
        ]},
    {"id":2,"name":"Orthographe","parent":null,
        "children":[
            {"id":8,"name":"Orthographe lexicale","parent":2,
                "children":[
                    {"id":11,"name":"Nombre","parent":8,"children":[]}]
            },
            {"id":9,"name":"Orthographe grammaticale","parent":2,
                "children":[{"id":10,"name":"Adjectif couleur","parent":9,"children":[]}]
            }
        ]
    }
]

问题!

例如,对于id = 20

的节点
 {"id":20,"name":"annalyse 2","parent":12,"children":[]}

我需要为此节点获取父节点id和名称,如下所示:

{"id":20,"name":"annalyse 2","parent":12,"children":[]
"parentNodes"= [{"id":1,"name":"Grammaire"},{"id":12,"name":"Annalyse grammaticale"},{"id":20,"name":"annalyse 2"}]
}

我不想要循环解决方案,因为我已经制作并制作了我的代码错误,因为我需要克隆这个对象。

欢迎任何帮助,我知道我必须做一个递归函数谁添加“路径”但我失败直到现在 谢谢

1 个答案:

答案 0 :(得分:0)

可能需要一些修复但是有效!

 function setPath(array){
      function initPath(node,liste){
            liste.push({"id":node.id,"name":node.name});
            node["path"] = tools_clone(liste) ;
            for(var n in node.children){
                 initPath(node.children[n],tools_clone(liste));
            }
      }

      for(var i = 0; i < array.length; i++) {
            var p = [];
            initPath(array[i],p);
      }
 }

var r = convert(originals);
setPath(r);