简体   繁体   English

在Typescript中将数组转换为树

[英]Convert an Array to Tree in Typescript

I have structure database in array of objects stored like this: 我在这样存储的对象数组中有结构数据库:

 arry = [{"name": "a", "id": "2", "data":"foo", "parent": "1"},
 {"name": "b", "id": "3", "data":"foo", "parent": "2"},
 {"name": "c", "id": "4", "data":"foo", "parent": "3"},
 {"name": "d", "id": "5", "data":"foo", "parent": "3"},
 {"name": "e", "id": "6", "data":"foo", "parent": "4"},
 {"name": "f", "id": "7", "data":"foo", "parent": "5"}]

I want nested structure like this 我想要这样的嵌套结构

{
"2":{
   "name": "a",
   "data": "foo",
  "3":{
     "name": "b",
     "data":"foo",
     "4":{
        "name": "c",
        "data":"foo",
        "6":{
           "name": "e",
           "data": "foo",
          };
       },
      "5":{
         "name": "d",
         "data": "foo",
         "7":{
            "name": "f",
            "data": "foo"
           }
        }
      }
    }
  };

so I can use it Angular Material tree. 所以我可以使用它Angular Material树。

To do this, you can reduce your array of nodes to a dictionary, using each node's id as index. 为此,您可以使用每个节点的id作为索引,将节点数组简化为字典。

This way, you'll have all the nodes accessible by their id directly on the dictionary. 这样,您将可以通过字典的ID直接访问所有节点。 You'll thus be able to store each node in its parent easily. 因此,您将能够轻松地将每个节点存储在其父节点中。

Once all the nodes are stored in their respective parent, you just have to grab the root node from the dictionary, it will hold all your tree. 一旦所有节点都存储在各自的父节点中,您只需从字典中获取根节点,它将保存您所有的树。

It may happen that the parent isn't yet in the dictionary when you parse the child, in this case, you can use a dummy object that will play a placeholder the time we come to parse the actual parent node. 解析子级时,可能会发生父级不在字典中的情况,在这种情况下,您可以使用一个虚拟对象,该对象将在我们解析实际父级节点时扮演一个占位符。

 var arry = [ {"name": "a", "id": "2", "data":"foo", "parent": "1"}, {"name": "b", "id": "3", "data":"foo", "parent": "2"}, {"name": "c", "id": "4", "data":"foo", "parent": "3"}, {"name": "d", "id": "5", "data":"foo", "parent": "3"}, {"name": "e", "id": "6", "data":"foo", "parent": "4"}, {"name": "f", "id": "7", "data":"foo", "parent": "5"} ]; function totree(branches, node) { // if we don't have the parent yet if (!branches[node.parent]) { // create a dummy placeholder for now branches[node.parent] = {}; } // store our node in its parent branches[node.parent][node.id] = node; // store our node in the full list // copy all added branches on possible placeholder branches[node.id] = Object.assign(node, branches[node.id]); return branches; } var tree = arry.reduce(totree, {})['1']; // get only the root node ('1') console.log(tree); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM