我为每个数据时间编写了这个简单的过滤器数组,但不确定这是否是个好方法。
示例数据:
[
{
"content": "test1",
"createdAt": "2020-05-29T13:46:14.000Z"
},
{
"content": "test2",
"createdAt": "2020-05-29T13:46:14.000Z"
},
{
"content": "test3",
"createdAt": "2020-05-27T13:46:14.000Z"
}
]
我想像这样转换它:
{
"Fri May 29 2020": [
{
"content": "test1",
"createdAt": "2020-05-29T13:46:14.000Z"
},
{
"content": "test2",
"createdAt": "2020-05-29T13:46:14.000Z"
}
],
"Wed May 27 2020": [
{
"content": "test3",
"createdAt": "2020-05-27T13:46:14.000Z"
}
]
}
还有我的代码:
let usedDates = new Set();
let logs = {};
for(let log of data) {
const date = new Date(log.createdAt).toDateString();
if(usedDates.has(date)) continue;
logs[date] = data.filter((e) => date == new Date(e.createdAt).toDateString());
usedDates.add(date);
}
是的,它有效,但不确定它是否是好方法。
最佳答案
这个简单的reduce
技巧可以帮助您
const data = [
{
"content": "test1",
"createdAt": "2020-05-29T13:46:14.000Z"
},
{
"content": "test2",
"createdAt": "2020-05-29T13:46:14.000Z"
},
{
"content": "test3",
"createdAt": "2020-05-27T13:46:14.000Z"
}
]
const result = data.reduce((acc, value) => {
const date = new Date(value.createdAt);
const dateFormatted = date.toDateString();
acc[dateFormatted] = [...(acc[dateFormatted] || []), value];
return acc;
}, {})
console.log(result);
关于javascript - 如何按日期时间优化数组过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62090358/