js数组格式转换问题

如何将上面这个数据,转换成下面这种,初学者,表示好难,还请各位老哥答疑解惑
------------------------------

回答

哥们,你们说我做的对吗

编辑一下,建议题主下次贴代码,不要放截图,谢谢。

arr.reduce((acc, cur) => {

const { year, month } = cur;

let targetYearObj = acc.find((item) => item.year === year);

if (!targetYearObj) {

targetYearObj = { year, list: [] };

acc.push(targetYearObj);

}

let targetMonthObj = targetYearObj.list.find((item) => item.month === month);

if (!targetMonthObj) {

targetMonthObj = { month, children: [] };

targetYearObj.list.push(targetMonthObj);

};

targetMonthObj.children.push(cur);

return acc;

}, []);

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

以上是 js数组格式转换问题 的全部内容, 来源链接: utcz.com/a/38846.html

回到顶部