score:1

Accepted answer

You could take an iterative approach by storing all know information, lije parent and children in an object and get then obly the root children.

var data = [{ node_id: 1, token: "Google", parent_node: { parent_node: 2, name: "News" } }, { node_id: 2, token: "News", parent_node: { parent_node: 3, name: "is" } }, { node_id: 3, token: "is", parent_node: { parent_node: -1, name: null } }, { node_id: 4, token: "a", parent_node: { parent_node: 6, name: "aggregator" } }, { node_id: 5, token: "news", parent_node: { parent_node: 6, name: "aggregator" } }, { node_id: 6, token: "aggregator", parent_node: { parent_node: 3, name: "is" } }, { node_id: 7, token: "and", parent_node: { parent_node: 6, name: "aggregator" } }, { node_id: 8, token: "app", parent_node: { parent_node: 6, name: "aggregator" } }, { node_id: 9, token: "developed", parent_node: { parent_node: 6, name: "aggregator" } }, { node_id: 10, token: "by", parent_node: { parent_node: 9, name: "developed" } }, { node_id: 11, token: "Google", parent_node: { parent_node: 10, name: "by" } }],
    tree = function (data, root) {
        var o = {};
        data.forEach(function ({ node_id: id, token: name, parent_node: { parent_node: parent } }) {
            var temp = { name };
            if (o[id] && o[id].children) {
                temp.children = o[id].children;
            }
            o[id] = temp;
            o[parent] = o[parent] || {};
            o[parent].children = o[parent].children || [];
            o[parent].children.push(temp);

        });
        return o[root].children;
    }(data, -1);

console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Related Query

More Query from same tag