我有一个对象,其中包含两名员工的工作日期数组,由他们的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 }
})}
})}
由于
答案 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;