user1053419
user1053419

Reputation:

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: {}
        }
    }
}

Upvotes: 1

Views: 292

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386680

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; }

Upvotes: 0

grawity_u1686
grawity_u1686

Reputation: 16542

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.

Upvotes: 0

Lux
Lux

Reputation: 18240

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));

Upvotes: 1

Related Questions