我有一组像这样的对象:
entries: [
{
id:1,
text: "Lorem ipsum",
timeStamp:"Thu, 01 Jun 2018"
},
{
id:3,
text:"Lorem ipsum",
timeStamp:"Thu, 24 May 2018"
},
{
id:4,
text: "Lorem ipsum",
timeStamp:"Thu, 24 May 2018"
}
]
现在我希望能够将它们分组到一个'存档'像这样的数组:
archive: [
{
monthyear: May 2018,
entries: 2
},
{
monthyear: June 2018,
entries: 5
}
]
想知道我应该使用什么类型的数组函数来获得预期的结果。
答案 0 :(得分:2)
您可以使用reduce
方法按日期和toLocaleString
方法对数组项进行分组,以获得月份和年份。
const data = [{"id":1,"text":"Lorem ipsum","timeStamp":"Thu, 01 Jun 2018"},{"id":3,"text":"Lorem ipsum","timeStamp":"Thu, 24 May 2018"},{"id":4,"text":"Lorem ipsum","timeStamp":"Thu, 24 May 2018"}]
const result = data.reduce((r, {timeStamp}) => {
let dateObj = new Date(timeStamp);
let monthyear = dateObj.toLocaleString("en-us", { month: "long", year: 'numeric' });
if(!r[monthyear]) r[monthyear] = {monthyear, entries: 1}
else r[monthyear].entries++;
return r;
}, {})
console.log(Object.values(result))