gpt4 book ai didi

javascript - 将数组扁平化为一个对象,同时减少一个属性

转载 作者:行者123 更新时间:2023-11-30 15:10:00 25 4
gpt4 key购买 nike

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

谢谢

最佳答案

您可以为此使用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;

关于javascript - 将数组扁平化为一个对象,同时减少一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45243530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com