简体   繁体   English

在打字稿中将关系数组转换为树对象

[英]Convert An Relational Array to Tree Object in Typescript

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

array = [ {"name": "a", "id": "1",  "parentId": NULL},
 {"name": "b", "id": "2", "parentId": "1"},
 {"name": "c", "id": "3", "parentId": "1"},
 {"name": "d", "id": "4", "parentId": "1"},
 {"name": "e", "id": "5", "parentId": "2"},
 {"name": "f", "id": "6", "parentId": "3"},
 {"name": "g", "id": "7", "parentId": "3"},
 {"name": "h", "id": "8", "parentId": "4"},
 {"name": "j", "id": "9", "parentId": "4"}]


And I want to get like this tree object;我想得到这个树对象;

{
    a: {
        b: {
            e: {}
        },
        c: {
            f: {},
            g: {}
        },
        d: {
            h: {},
            j: {}
        }
    }
}

you can use recursion:您可以使用递归:

buildTree(arr, root) {
  return {
    [root.name]: arr
      .filter(x => x.parentId === root.id)
      .map(x => buildTree(x))
      .reduce((a, b) => ({ ...a, ...b }), {}),
  };
}

const tree = buildTree(array, array.find(x => !x.parentId));

Possible implementation:可能的实现:

function grow(items) {
    var things = {"": {}};
    for (var i of items) {
        things[i.id] = {};
    }
    for (var i of items) {
        things[i.parentId || ""][i.name] = things[i.id];
    }
    return things[""];
}

The two loops could be merged if there is a guarantee that the parent always precedes its children.如果保证父级始终在其子级之前,则可以合并两个循环。

You could take a single loop and respect the parents as well.您也可以进行一次循环并尊重父母。

This approach works with unsorted data as well.这种方法也适用于未排序的数据。

 var array = [{ name: "a", id: "1", parentId: null }, { name: "b", id: "2", parentId: "1" }, { name: "c", id: "3", parentId: "1" }, { name: "d", id: "4", parentId: "1" }, { name: "e", id: "5", parentId: "2" }, { name: "f", id: "6", parentId: "3" }, { name: "g", id: "7", parentId: "3" }, { name: "h", id: "8", parentId: "4" }, { name: "j", id: "9", parentId: "4" }], tree = function (data, root) { var o = {}; data.forEach(({ name, id, parentId }) => { o[id] = o[id] || {}; o[parentId] = o[parentId] || {}; o[parentId][name] = o[id]; }); return o[root]; }(array, null); console.log(tree);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

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

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