简体   繁体   English

在javascript中将数组转换为嵌套对象

[英]Converting an array into a nested object in javascript

I have typical organization hierarchy .我有典型的组织hierarchy For example.例如。

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

A is the top most node. A 是最顶端的节点。 But I receive 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 in to single nested object or a tree .但我想将其转换为single nested objecttree A root node has children attribute with the children embedded and each child has its own children attribute like this.根节点具有带有子节点的子节点属性,并且每个子节点都有自己的子节点属性,如下所示。

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

How can I do this in javascript efficiently?我怎样才能有效地在 javascript 中做到这一点?

Unlike the other solutions, this uses a single loop - the order of data is unimportant - example is not in the same order as 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);

This solution features Jaromanda X' solution with some additions.该解决方案具有 Jaromanda X'解决方案和一些附加功能。

  1. Array.prototype.reduce instead of Array.prototype.forEach , because of the need of a temporary variable and the return value. Array.prototype.reduce而不是Array.prototype.forEach ,因为需要一个临时变量和返回值。

  2. The content of r[a.name].children is preserved and assigned to a.children . r[a.name].children a.children的内容被保留并分配给a.children

  3. Node a is assigned to r[a.name] .节点a被分配给r[a.name] Therefore all properties of the node object remain, like prop1 ... prop5 .因此,节点对象的所有属性都保留下来,例如prop1 ... prop5

  4. The root node is assigned to r._ for later use.将根节点分配给r._供以后使用。

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

For more than one roots, you could use the parent of root as accessor for the children and return this array对于多个根,您可以使用根的父级作为子级的访问器并返回此数组

 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' }, { name: "A1", parent: null, prop3: 'prop3' }], tree = data.reduce(function (r, a) { if (r[a.name] && r[a.name].children) { // prevent empty children array a.children = r[a.name].children; } r[a.name] = a; r[a.parent] = r[a.parent] || {}; r[a.parent].children = r[a.parent].children || []; r[a.parent].children.push(a); return r; }, {}).null.children; // take root value as property accessor console.log(tree);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

You can do this using while loop:您可以使用 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);

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

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