我有以下数据:
const rawData=[
{
Order_Date: "2020-08-11",
Region: "South",
Product_Name: "Bookcase",
Sales: 261.96
},
{
Order_Date: "2020-08-13",
Region: "South",
Product_Name: "Stacking Chairs",
Sales: 731.94
},
{
Order_Date: "2020-10-06",
Region: "South",
Product_Name: "Stacking Chairs",
Sales: 700.45
},
{
Order_Date: "2020-12-06",
Region: "East",
Product_Name: "Self-Adhesive Address Labels for Typewriters by Universal",
Sales: 14.62
},
{
Order_Date: "2019-11-15",
Region: "East",
Product_Name: "Table",
Sales: 957
},
{
Order_Date: "2019-11-10",
Region: "East",
Product_Name: "Eldon Fold",
Sales: 22
}
]
预期输出:
[
{
Region: "South",
data: [
{
Order_Date: "2020-08",
Sales: 993.90
},
{
Order_Date: "2020-10",
Sales: 700.45
},
]
},
{
Region: "East",
data: [
{
Order_Date: "2019-11",
Sales: 989
},
{
Order_Date: "2020-12",
Sales: 14.62
},
]
}
]
我想首先按地区分组,对于每个地区我想按 Order_Date 的年月('YYYY-MM')分组,并按每个 Order_Date('YYYY-MM') 组的销售额求和。
我尝试了以下代码,但无法获得预期的输出。我不明白如何通过多个分组来做到这一点。
const groupByRegion = _(rawData).groupBy('Region').value();
const groupByRegionDate = _.forEach(groupByRegion, (value, key) => {
groupByRegion[key] = _.groupBy(groupByRegion[key], (item) =>
moment(item.Order_Date).startOf('month').format('YYYY-MM')
);
});