我有一个名为items的数组,它包含29个项。每个项目都有一个日期、名称、代码和星期号。我正试着用打字本把这些项目按周数分组。有人能帮忙吗?
这就是我的阵列当前的样子:
items:
0:
code: "N"
date: "2020-10-13T01:00:00.000Z"
name: "Tuesday"
week: 7
1:
code: "N"
date: "2020-10-13T01:00:00.000Z"
name: "Tuesday"
week: 7
2: {date: "2020-10-12T01:00:00.000Z", name: "Monday", code: "O", …}
3: {date: "2020-10-12T01:00:00.000Z", name: "Monday", code: "O", …}
ETC-最高可达29。然而,我希望它按周分组如下。有人知道怎么做吗?
weeks:
0:
days:
0:{name:Monday, date: ####, code:###}
0:{name:Tuesday, date: ####, code:###}
1:
days:
0:{name:Monday, date: ####, code:###}
0:{name:Tuesday, date: ####, code:###}
2:
days:
0:{name:Monday, date: ####, code:###}
0:{name:Tuesday, date: ####, code:###}
要么使用lodash
包中的groupBy
(带一点后处理(,要么像这样简单地使用for
:
const weeks: Record<string, any> = {};
for (const item of items) {
if (!weeks[item.week]) {
weeks[item.week] = {
days: []
}
}
weeks[item.week].days.push({
name: item.name,
date: item.date,
code: item.code
})
}
注意:不要使用any
,而应该使用days数组道具来指示一些类型,其中每个元素都有名称、日期和代码道具