按相同的属性值对数组进行分组,遍历该数组

时间:2017-07-20 19:26:40

标签: javascript arrays reactjs

我有以下数组:

var results = [
  { group: 1,
    department: 2,
    total: 10 },
  { group: 1,
    department: 2,
    total: 25 },
  { group: 1,
    department: 3, 
    total: 15 },
  { group: 1,
    department: 3,
    total: 5 },
  { group: 2,
    department: 4,
    total: 10},
  { group: 2,
    department: 4, 
    total: 50 }
]

我需要将数组排列成2D嵌套数组,其中子数组是第1组和第2组。子数组也应该是父数组,其子项按Department排序,如下所示:

var results:[  
   {  
      group1:[  
         {  
            department2:[  
               {  
                  group:1,
                  department:2,
                  total:10
               },
               {  
                  group:1,
                  department:2,
                  total:25
               },
               {  
                  group:1,
                  department:3,
                  total:15
               }
            ]
         },
         {  
            department3:[  
               {  
                  group:1,
                  department:3,
                  total:5
               }
            ]
         }
      ]
   },
   {  
      group2:[  
         {  
            department4:[  
               {  
                  group:2,
                  department:4,
                  total:10
               },
               {  
                  group:2,
                  department:4,
                  total:50
               }
            ]
         }
      ]
   }
]

这是一个反应组件,我需要将每个组件作为一行打印,但在完成所有部门组之后添加一个总计,然后在每个组之后添加一个,然后在所有部分之后添加总计。

也许我过于复杂并且有更好的方法?

2 个答案:

答案 0 :(得分:1)

var results = [
  { group: 1,
    department: 2,
    total: 10 },
  { group: 1,
    department: 2,
    total: 25 },
  { group: 1,
    department: 3, 
    total: 15 },
  { group: 1,
    department: 3,
    total: 5 },
  { group: 2,
    department: 4,
    total: 10},
  { group: 2,
    department: 4, 
    total: 50 }
]

var nested_result = {}

results.forEach(obj => {
  if(nested_result[obj.group] === undefined) {
    nested_result[obj.group] = {};
  }
  if(nested_result[obj.group][obj.department] === undefined) {
    nested_result[obj.group][obj.department] = [];
  }
  nested_result[obj.group][obj.department].push(obj);
})

console.log(nested_result);

答案 1 :(得分:1)



var results = [
    { group: 1, department: 2, total: 10 },
    { group: 1, department: 2, total: 25 },
    { group: 1, department: 3, total: 15 },
    { group: 1, department: 3, total: 5 },
    { group: 2, department: 4, total: 10},
    { group: 2, department: 4, total: 50 }
]

var outObj = {};
var out = results.map(function(a) {
    var groupName = 'group' + a.group;
    typeof outObj[groupName] == 'undefined' && ( outObj[groupName] = {});
    var depName = 'department' + a.department;
    typeof outObj[groupName][depName] == 'undefined' && ( outObj[groupName][depName]  = [] );
    outObj[groupName][depName].push(a );
});

console.log( outObj );