将数组展平为一个对象,同时减少一个属性

时间:2017-07-21 17:31:40

标签: javascript arrays

我有一个对象,其中包含两名员工的工作日期数组,由他们的id组成。

var employeeWorkedHours = {
  1: [
     { employeeId: 1, hours: 1, date: 7/1/2017},
     { employeeId: 1, hours: 2, date: 7/2/2017},
     { employeeId: 1, hours: 3, date: 7/3/2017},
     { employeeId: 1, hours: 4, date: 7/4/2017},
     { employeeId: 1, hours: 5, date: 7/5/2017}
],
2: [
   { employeeId: 2, hours: 5, date: 7/1/2017},
   { employeeId: 2, hours: 4, date: 7/2/2017},
   { employeeId: 2, hours: 3, date: 7/3/2017},
   { employeeId: 2, hours: 2, date: 7/4/2017},
   { employeeId: 2, hours: 1, date: 7/5/2017}
] }

我想迭代它,并将每个数组合并为一个对象:

Object.keys(employeeWorkedHours).map((emp) => { 
  emp.map((day) => {
    // expected output: one single object
    // { employeeId: X, totalHours: sum of hours of each line }
  })}
})}

由于

1 个答案:

答案 0 :(得分:2)

您可以使用reduce

const employeeWorkedHours = {
  1: [
     { employeeId: 1, hours: 1, date: 7/1/2017},
     { employeeId: 1, hours: 2, date: 7/2/2017},
     { employeeId: 1, hours: 3, date: 7/3/2017},
     { employeeId: 1, hours: 4, date: 7/4/2017},
     { employeeId: 1, hours: 5, date: 7/5/2017}
],
2: [
   { employeeId: 2, hours: 5, date: 7/1/2017},
   { employeeId: 2, hours: 4, date: 7/2/2017},
   { employeeId: 2, hours: 3, date: 7/3/2017},
   { employeeId: 2, hours: 2, date: 7/4/2017},
   { employeeId: 2, hours: 1, date: 7/5/2017}
] };

const result = Object.keys(employeeWorkedHours).map((emp) => { 
  return employeeWorkedHours[emp].reduce((acc, day) => {
    acc.totalHours += day.hours;
    return acc;
  }, {employeeId: +emp, totalHours: 0} );  
});

console.log(result);

解释

Object.keys(employeeWorkedHours)将给出外部对象的属性名称数组,因此["1", "2"]。在map回调中,emp将获得这两个值中的每一个。所以employeeWorkedHours[emp]是与该键相关联的数组。

然后reduce将构建并返回该员工的所需对象,如下所示:它以值{employeeId: +emp, totalHours: 0}reduce的第二个参数)开始,这将成为该员工的第一个参数回调,即acc。回调的第二个参数采用该员工的每个内部对象的值(例如{ employeeId: 1, hours: 1, date: 7/1/2017})。该条目的小时数将添加到正在累积的对象(到acc)。变异的acc对象再次返回到reduce内部,它会将其传递给下一次回调调用。因此,对象最终确定并最终由reduce返回。

reduce的结果将返回到map内部,而内部结果将返回一个结果数组:每个员工一个值(对象)。

假设

我假设主对象的属性对应于内部对象的employeeId。如果不是这种情况,那么您需要添加:

acc.employeeId = day.employeeId;