Convert array to nested object in javascript

I have a typical organization hierarchy. For example.

D,E is reporting to B. B,C is reporting to A.

A is the topmost node. But I get this data as a flat array with an attribute pointing to the parent.

    [{
      name: "A",
      parent: null
    },
    {
      name: "B",
      parent: "A"
    },
    {
      name: "C",
      parent: "A"
    },
    {
      name: "D",
      parent: "B"
    },
    {
      name: "E",
      parent: "B"
    }]

But I want to convert this to single nested objector tree. The root node has a child attribute with built-in children, and each child has its own child attribute similar to this.

    {
      name: "A",
      children: [{
        name: "C"
        children: [{
          name: "D"
        },{
          name: "E"
        }]
      },{
        name: "C"
      }]
    }

How can I do this in javascript efficiently?

+4
source share
3 answers

Unlike other solutions, this uses a single loop - the data order is not important - the example is not in the same order as the question

var peeps = [
    { name: "D", parent: "B" }, 
    { name: "B", parent: "A" },
    { name: "A", parent: null }, 
    { name: "C", parent: "A" }, 
    { name: "E", parent: "B" }
];

var tree;
var obj = {};
peeps.forEach(function (peep) {
    var name = peep.name,
        parent = peep.parent,
        a = obj[name] || { name: name };
    if (parent) {
        obj[parent] = obj[parent] || { name: parent };
        obj[parent].children = obj[parent].children || [];
        obj[parent].children.push(a);
    } else {
        tree = obj[name];
    }
    obj[name] = obj[name] || a;
});
console.log(tree);
+5

, while:

var data = [
    { name: "A", parent: null },
    { name: "B", parent: "A" },
    { name: "C", parent: "A" },
    { name: "D", parent: "B" },
    { name: "E", parent: "B" }
];

var root = data.find(function(item) {
    return item.parent === null;
});

var tree = {
    name: root.name
};

var parents = [tree];
while (parents.length > 0) {
    var newParents = [];
    parents.forEach(function(parent) {
        var childs = data.filter(function(item) {
            return item.parent == parent.name
        }).forEach(function(child) {
            var c = { name: child.name };
            parent.children = parent.children || [];
            parent.children.push(c);
            newParents.push(c);
        });
    });
    parents = newParents;
}

console.log(tree);
+2

Jaromanda X ' .

  • Array.prototype.reduceinstead Array.prototype.forEach, due to the need for a temporary variable and return value.

  • Content is r[a.name].childrensaved and assigned a.children.

  • Node is aassigned r[a.name]. Therefore, all of the properties of the object node are like prop1... prop5.

  • The root node is assigned r._for later use.

var data = [
        { name: "D", parent: "B", prop1: 'prop1' },
        { name: "B", parent: "A", prop2: 'prop2' },
        { name: "A", parent: null, prop3: 'prop3' },
        { name: "C", parent: "A", prop4: 'prop4' },
        { name: "E", parent: "B", prop5: 'prop5' }
    ],
    tree = data.reduce(function (r, a) {
        a.children = r[a.name] && r[a.name].children;
        r[a.name] = a;
        if (a.parent) {
            r[a.parent] = r[a.parent] || {};
            r[a.parent].children = r[a.parent].children || [];
            r[a.parent].children.push(a);
        } else {
            r._ = a;
        }
        return r;
    }, {})._;
document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
Run code
+2
source

Source: https://habr.com/ru/post/1623431/


All Articles