当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《在javascript中将数组转换为嵌套对象》经验,为你挑选了1个好方法。

我有典型的组织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中执行此操作?



1> 小智..:

与其他解决方案不同,它使用单个循环 - 数据顺序不重要 - 示例与问题的顺序不同

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

推荐阅读
mobiledu2402851373
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有