我对React很新。基本上我试图为每张收据显示一张收据表,其中包含以下属性:
{
date: '2017-07-03',
description: 'Receipt description,
amount: 300
}
我试图将收据拆分并按如下顺序排列:
2017
July
03 Jul | Receipt Description | £300.00
------ | ------------------- | -------
01 Jul | Receipt Description | £20.00
May
03 May | Receipt Description | £300.00
------ | ------------------- | -------
01 May | Receipt Description | £20.00
2016
...
我可以轻松地映射对象并按日期排序,但无法弄清楚如何将它们拆分为年份和月份部分。任何指导都会非常感激!
答案 0 :(得分:0)
你可以这样做:
var sorted = data.sort(function(a, b) {
return new Date(a.date) - new Date(b.date);
});
var byYearAndByMonth = {};
_.each(sorted, function(item) {
var year = item.date.substring(0,4)
var month = item.date.substring(5,7)
if (typeof byYearAndByMonth[year] === "undefined") {
byYearAndByMonth[year] = {};
}
if (typeof byYearAndByMonth[year][month] === "undefined") {
byYearAndByMonth[year][month] = [];
}
byYearAndByMonth[year][month].push(item);
});
首先对数组进行排序,然后循环遍历排序的数组,并按月建立一个对象索引。
然后,在render()
方法中映射对象,您必须使用Object.keys
请参阅此jsfiddle