我正在尝试解决一个问题,该问题需要包含信息的对象数组的排序。例如,将其转换为:
[
{
name: 'test1',
date: '2019-02-18T08:33:01.000Z',
},
{
name: 'test2',
date: '2019-02-19T08:33:01.000Z',
},
{
name: 'test3',
date: '2019-02-19T08:33:01.000Z',
},
]
对此:
{
'2019-02-18':{
name: 'test1'
},
'2019-02-19':[
{
name: 'test2',
},
{
name: 'test3',
}
]
}
我该如何实现?
答案 0 :(得分:0)
假设您要为每个date
分组的对象数组。一种替代方法是将Array.reduce()与String.match()
const input = [
{name: 'test1', date: '2019-02-18T08:33:01.000Z'},
{name: 'test2', date: '2019-02-19T08:33:01.000Z'},
{name: 'test3', date: '2019-02-19T08:33:01.000Z'}
];
let res = input.reduce((acc, {name, date}) =>
{
let [m, d] = date.match(/(.+)T/);
acc[d] = [...(acc[d] || []), {name}];
return acc;
}, {});
console.log(res);
答案 1 :(得分:-1)
这是按问题分组而不是排序。对象键也未排序。
function groupByDate(data) {
let result = {};
data.forEach((el) => {
let datePart = el.date.split("T")[0];
let value = result[datePart]
if(value) {
result[datePart].push({name: el.name})
} else {
result[datePart] = [{name: el.name}]
}
});
return result;
}
var dates = [
{
name: 'test1',
date: '2019-02-18T08:33:01.000Z',
},
{
name: 'test2',
date: '2019-02-19T08:33:01.000Z',
},
{
name: 'test3',
date: '2019-02-19T08:33:01.000Z',
},
];
console.log(groupByDate(dates));