我有一个日期时间数组-我需要一个对象,其中的键将日期分组,值应该是该日期的时间数组。来源:
[
"2019-02-18T11:30:00+01:00",
"2019-02-18T13:00:00+01:00",
"2019-02-19T13:30:00+01:00",
"2019-02-19T16:30:00+01:00",
"2019-02-20T17:00:00+01:00",
"2019-02-20T17:30:00+01:00",
"2019-02-20T18:00:00+01:00"
]
我需要这个:
{
'2019-02-18': [
'11:30:00+01:00',
'13:00:00+01:00'
],
'2019-02-19': [
'13:30:00+01:00',
'16:30:00+01:00'
],
...
}
一种解决方案是循环数组,剥离前10个字符并与其他日期时间匹配-tbh不太好。
答案 0 :(得分:2)
let data = ["2019-02-18T11:30:00+01:00","2019-02-18T13:00:00+01:00","2019-02-19T13:30:00+01:00","2019-02-19T16:30:00+01:00","2019-02-20T17:00:00+01:00","2019-02-20T17:30:00+01:00","2019-02-20T18:00:00+01:00"]
let op = data.reduce(( op, inp ) => {
let [key,value] = inp.split('T')
if( op[key] ){
op[key].push(value)
} else {
op[key] = [value]
}
return op
},{})
console.log(op)
答案 1 :(得分:1)
一种选择是将Array.reduce()与String.match()结合使用
const input = [
"2019-02-18T11:30:00+01:00",
"2019-02-18T13:00:00+01:00",
"2019-02-19T13:30:00+01:00",
"2019-02-19T16:30:00+01:00",
"2019-02-20T17:00:00+01:00",
"2019-02-20T17:30:00+01:00",
"2019-02-20T18:00:00+01:00"
];
let res = input.reduce((acc, date) =>
{
let [m, d, t] = date.match(/(.+)T(.+)/);
acc[d] = [...(acc[d] || []), t];
return acc;
}, {});
console.log(res);