javascript - 将数组转换为带有子对象的对象

标签 javascript arrays angularjs

我有一个包含 element idelement parent 字段的数组,如下所示:

[
  { id: 1, parent: 0 },
  { id: 2, parent: 0 },
  { id: 3, parent: 0 },
  { id: 4, parent: 3 },
  { id: 5, parent: 3 },
  { id: 6, parent: 5 },
  { id: 7, parent: 6 },
]

我想像这样隐藏这个数组:

[
  { id: 1, childs: null },
  { id: 2, childs: null },
  { id: 3, childs:
    [
      { id: 4, childs: null },
      { id: 5, childs: 
        [
          { id: 6, childs: 
            [
              { id: 7, childs: null }
            ] // 6 .childs
          }, // 6
        ] // 5.childs
      }, // 5
    ] // 3.childs
  }, // 3
]

换句话说,将第一个数组视为评论列表,我想使用 Angular 的 ng-repeat 指令和嵌套的 ng-repeats 来显示主题,以显示子评论。

那么我怎样才能以正确的方式和良好的性能将第一个数组转换为第二个数组呢?

最佳答案

一个干净的方法是使用 map/reduce。

var array = [
  { id: 1, parent: 0 },
  { id: 2, parent: 0 },
  { id: 3, parent: 0 },
  { id: 4, parent: 3 },
  { id: 5, parent: 3 },
  { id: 6, parent: 5 },
  { id: 7, parent: 6 },
];

array.map(function(el){
  el.children = array.filter(function(item){
    return item.parent === el.id
  });
  return el;
}).filter(function(item){
  return item.parent === 0;
})

结果是:

[
   {
      "id":1,
      "parent":0,
      "children":[

      ]
   },
   {
      "id":2,
      "parent":0,
      "children":[

      ]
   },
   {
      "id":3,
      "parent":0,
      "children":[
         {
            "id":4,
            "parent":3,
            "children":[

            ]
         },
         {
            "id":5,
            "parent":3,
            "children":[
               {
                  "id":6,
                  "parent":5,
                  "children":[
                     {
                        "id":7,
                        "parent":6,
                        "children":[

                        ]
                     }
                  ]
               }
            ]
         }
      ]
   }
]

过滤您需要的属性取决于您,这可以通过再次映射这些元素轻松完成:)

P.S.:就渐近复杂性而言,这不是最佳解决方案,但它简短而优雅。

关于javascript - 将数组转换为带有子对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35416827/

相关文章:

javascript - 如何使用 JSHint 显示 JavaScript 错误?

javascript - OOP javascript 存储功能如何

javascript - 这些东西中的一个与另一个不一样......在一个数组中?

c# - 如何在 C# 中_直接_将基数为 10(十进制)的字符串转换为字节数组?

javascript - 装饰 $errorProvider 时的循环引用

javascript - AngularJS 1.4 : Select List Value not Initializing Correctly when List is Inserted with $compile

javascript - Angular Checkbutton 行为错误

javascript - 获取对特定属性具有相同值的对象列表

javascript - angular.js 路由在服务器上不起作用

java - 在java中编写一个连续的 'for'循环