我有以下对象数组:
[{
id: 1,
amount: 2000,
date: "2018-01-31T00:00:00.000Z"
},{
id: 2,
amount: 3000,
date: "2017-07-31T00:00:00.000Z"
},{
id: 3,
amount: 6000,
date: "2018-01-31T00:00:00.000Z"
},{
id: 4,
amount: 7000,
date: "2017-01-31T00:00:00.000Z"
},{
id: 5,
amount: 5000,
date: "2017-03-31T00:00:00.000Z"
},{
id: 6,
amount: 3000,
date: "2018-02-22T00:00:00.000Z"
},{
id: 7,
amount: 4500,
date: "2017-01-31T00:00:00.000Z"
}]
我正在调用以下命令按年份和日期对对象进行分组:
_(data)
.groupBy(o => new Date(o.date).getFullYear() + '-' + new Date(o.date).getMonth())
.map(o1 => _(o1).map(o2 => o2.amount).sum())
代码以上给了我一个像[xx,yy,aaa,bbb,...]这样的总和数组。
现在,我需要确保这些数组中的值将被排序(2018-2的总和将是最先的,2017-1的总和将在最后)。
当结果包含按我上面描述的排序对象数组时,也会很好,每个对象还将包含期间键“年份-月份”以检测当前值。预期输出将是这样的:
[
{period: "2018-2", amount:3000}, // sum of 2018-2
{period: "2018-1", amount: 8000 }, // sum of 2018-1
{period: "2017-7", amount: 3000} // sum of 2017-7
{period: "2017-3", amount: 5000} // sum of 2017-3
{period: "2017-1" amount: 11500} // sum of 2017-1
]
可以编辑此链接以获得所需结果吗?谢谢!
{amount: xxx, period: "xxx" }
,但我的尝试都没有成功。 - stack001 stack001