我需要帮助来显示按日期分组的数组项。我有以下几项数组,每个项都有“今天”字段。
var originalArray = [
{title: "New Three 123", status: "pending", isDone: false, today: "2018-02-20T16:40:17.759Z", _id: "Eyt44n1svxIjOn5Y"},
{title: "My First card", status: "pending", isDone: false, today: "2018-02-21T13:00:13.979Z", _id: "UlSoOrLBjX2RldgQ"},
{title: "Sun Pharma", status: "completed", isDone: true, today: "2018-02-20T16:41:19.040Z", _id: "VbBEyndCIhPDB1Uf"},
{title: "Design News", status: "pending", isDone: false, today: "2018-02-21T13:00:07.730Z", _id: "rpW4bVIYWjlPMgk6"},
{title: "Amul India sddsd", status: "pending", isDone: false, today: "2018-02-20T16:41:13.087Z", _id: "uyISWNb7vapmRrNG"}
]
要求的输出是需要按日期分组的记录,写在数组项的“今天”键字段中:
var outputRequired = {
'2018,2,20' : [
{title: "New Three 123", status: "pending", isDone: false, today: "2018-02-20T16:40:17.759Z", _id: "Eyt44n1svxIjOn5Y"},
{title: "Sun Pharma", status: "completed", isDone: true, today: "2018-02-20T16:41:19.040Z", _id: "VbBEyndCIhPDB1Uf"},
{title: "Amul India sddsd", status: "pending", isDone: false, today: "2018-02-20T16:41:13.087Z", _id: "uyISWNb7vapmRrNG"}
],
'2018,2,21' : [
{title: "My First card", status: "pending", isDone: false, today: "2018-02-21T13:00:13.979Z", _id: "UlSoOrLBjX2RldgQ"},
{title: "Design News", status: "pending", isDone: false, today: "2018-02-21T13:00:07.730Z", _id: "rpW4bVIYWjlPMgk6"}
]
}
请指导我如何实现此输出。
谢谢, 吉涅什·拉瓦尔
最佳答案
您可以使用.reduce
来获得想要的结果。将 initialValue 设置为 {}
并在每次迭代中检查日期键是否存在。如果它存在附加到数组,否则在累加器中创建一个新数组。
var data = originalArray.reduce(
(acc, el)=>{
var today = el.today.split("T")[0].replace(/-/g, ",");
if(acc.hasOwnProperty(today)) acc[today].push(el);
else acc[today] = [el];
return acc;
}, {}
)
在这里查看工作代码:
var originalArray = [{
title: "New Three 123",
status: "pending",
isDone: false,
today: "2018-02-20T16:40:17.759Z",
_id: "Eyt44n1svxIjOn5Y"
},
{
title: "My First card",
status: "pending",
isDone: false,
today: "2018-02-21T13:00:13.979Z",
_id: "UlSoOrLBjX2RldgQ"
},
{
title: "Sun Pharma",
status: "completed",
isDone: true,
today: "2018-02-20T16:41:19.040Z",
_id: "VbBEyndCIhPDB1Uf"
},
{
title: "Design News",
status: "pending",
isDone: false,
today: "2018-02-21T13:00:07.730Z",
_id: "rpW4bVIYWjlPMgk6"
},
{
title: "Amul India sddsd",
status: "pending",
isDone: false,
today: "2018-02-20T16:41:13.087Z",
_id: "uyISWNb7vapmRrNG"
}
];
var data = originalArray.reduce(
(acc, el)=>{
var today = el.today.split("T")[0].replace(/-/g, ",");
if(acc.hasOwnProperty(today)) acc[today].push(el);
else acc[today] = [el];
return acc;
}, {}
)
console.log(data);
关于JavaScript - 按日期对对象数组或记录中的项目进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945753/