我有典型的组织hierarchy
.例如.
D,E is reporting to B. B,C is reporting to A.
A是最顶级的节点.但是我将这些数据作为一个平面数组接收,其属性指向父级.
[{ name: "A", parent: null }, { name: "B", parent: "A" }, { name: "C", parent: "A" }, { name: "D", parent: "B" }, { name: "E", parent: "B" }]
但是我希望将其转换为single nested object
或者tree
.根节点具有子属性,其中嵌入了子节点,并且每个子节点都有自己的子属性,如下所示.
{ name: "A", children: [{ name: "C" children: [{ name: "D" },{ name: "E" }] },{ name: "C" }] }
如何有效地在javascript中执行此操作?
与其他解决方案不同,它使用单个循环 - 数据顺序不重要 - 示例与问题的顺序不同
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);