如何将上面这个数据,转换成下面这种,初学者,表示好难,还请各位老哥答疑解惑
------------------------------
var list = [
{year: 2020, month: 8, title: 'sdfsdfadfs'},
{year: 2020, month: 8, title: '123213'},
{year: 2020, month: 8, title: '45645654'},
{year: 2020, month: 8, title: '67876'},
{year: 2020, month: 8, title: '09'},
{year: 2020, month: 7, title: '0000'},
{year: 2020, month: 7, title: 'asdf234'},
{year: 2020, month: 6, title: '23432'},
{year: 2019, month: 8, title: 'sdfsdfadfs'},
];
function groupBy(key, list, childKey='list') {
return Object.entries(list.reduce((res, v) => {
const group = res[ v[key] ];
if(group) group.push(v);
else res[v[key]] = [v];
return res;
}, {})).map(([value, group]) => ({[key]: value, [childKey]: group}));
}
groupBy('year', list).map(group => ({year: group.year, list: groupBy('month', group.list, 'children')}))
输出并不是按年降序的。如果有要求顺序可以加一个sort
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.4k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
编辑一下,建议题主下次贴代码,不要放截图,谢谢。