【发布时间】:2021-09-07 10:40:58
【问题描述】:
我有一个数组,我必须按月份年份对值进行分组,然后键入并返回 leavecount 字段的总数,
如果数组项 holidayWork 有值,则创建一个新类型:WOH。
我的数组:
[
{
"leavecount": 1,
"holidayWork": 0,
"dtAttendance": "2021-01-01T18:30:00.000Z",
"vchLeaveTypeName": "Work From Home",
"vchLeaveTypeAlias": "WFH",
"Year": "2021",
"mon": "Jan"
},
{
"leavecount": 1,
"holidayWork": 0,
"dtAttendance": "2021-02-03T18:30:00.000Z",
"vchLeaveTypeName": "Work From Home",
"vchLeaveTypeAlias": "WFH",
"Year": "2021",
"mon": "Jan"
},
{
"leavecount": 1,
"holidayWork": 0,
"dtAttendance": "2021-02-04T18:30:00.000Z",
"vchLeaveTypeName": "Work From Home",
"vchLeaveTypeAlias": "WFH",
"Year": "2021",
"mon": "Feb"
},
{
"leavecount": 0.5,
"holidayWork": 0,
"dtAttendance": "2021-02-05T18:30:00.000Z",
"vchLeaveTypeName": "Earned Leave",
"vchLeaveTypeAlias": "EL",
"Year": "2021",
"mon": "Feb"
},
{
"leavecount": 1,
"holidayWork": 0,
"dtAttendance": "2021-03-06T18:30:00.000Z",
"vchLeaveTypeName": "Work From Home",
"vchLeaveTypeAlias": "WFH",
"Year": "2021",
"mon": "Mar"
},
{
"leavecount": 0.5,
"holidayWork": 0,
"dtAttendance": "2021-04-07T18:30:00.000Z",
"vchLeaveTypeName": "Work From Home",
"vchLeaveTypeAlias": "WFH",
"Year": "2021",
"mon": "Apr"
},
{
"leavecount": 1,
"holidayWork": 0,
"dtAttendance": "2021-04-10T18:30:00.000Z",
"vchLeaveTypeName": "Work From Home",
"vchLeaveTypeAlias": "WFH",
"Year": "2021",
"mon": "Apr"
},
{
"leavecount": 1,
"holidayWork": 0,
"dtAttendance": "2021-04-11T18:30:00.000Z",
"vchLeaveTypeName": "Work From Home",
"vchLeaveTypeAlias": "WFH",
"Year": "2021",
"mon": "Apr"
},
{
"leavecount": 0.5,
"holidayWork": 0,
"dtAttendance": "2021-05-12T18:30:00.000Z",
"vchLeaveTypeName": "Casual/Sick Leave",
"vchLeaveTypeAlias": "CL",
"Year": "2021",
"mon": "May"
},
{
"leavecount": 1,
"holidayWork": 1,
"dtAttendance": "2021-05-12T18:30:00.000Z",
"vchLeaveTypeName": "",
"vchLeaveTypeAlias": "",
"Year": "2021",
"mon": "May"
}
]
预期结果:
[
{
"Jan 2021" : [
{
"WFH" : 2
}
],
"Feb 2021" : [
{
"WFH" : 1
},
{
"EL" : 0.5
}
],
"Mar 2021" : [
{
"WFH" : 1
}
],
"Apr 2021" : [
{
"WFH" : 2.5
}
],
"May 2021" : [
{
"WFH" : 0.5
},
{
"WOH" : 0.5
}
]
}
]
我试过这段代码:
let results = leaves.reduce(function (r, a) {
r[a.mon+' '+a.vchYear] = r[a.mon+' '+a.vchYear] || [];
r[a.vchYear][a.mon][a.vchLeaveTypeAlias].push(a)
return r;
}, Object.create(null));
请帮忙 .................................................. ..................................................... ..................................................... .....................
【问题讨论】:
-
我无法理解您的预期结果。为什么 May 2021 有 WFH 属性,而它应该有 CL 属性。还有为什么 2021 年 5 月 的 WOH 属性是
0.5
标签: javascript arrays sorting