如何转换对象数组为React Nivo Bar Chart所需的年月分组聚合数据格式
数据转换实现方案
实现逻辑
- 第一步:提取原始数据中所有唯一的区域值,确保后续每个年月分组都能覆盖全部区域,缺失值默认填0
- 第二步:遍历原始数据,将日期截取为
YYYY-MM格式作为分组键,累加对应区域的销售额 - 第三步:将分组后的对象转换为目标数组格式,对每个分组补全所有区域字段,无销售额的区域赋值为0,销售额统一保留两位小数
可直接运行的代码实现
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-08-11", Region: "Central", Product_Name: "Table", Sales: 200 }, { Order_Date: "2020-08-11", Region: "East", Product_Name: "Chairs", Sales: 350 }, { Order_Date: "2020-10-06", Region: "South", Product_Name: "Stacking Chairs", Sales: 700.45 }, { Order_Date: "2020-10-06", Region: "Central", Product_Name: "Chairs", Sales: 500 }, { 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 } ] // 提取所有唯一区域 const allRegions = [...new Set(rawData.map(item => item.Region))]; // 按年月分组累加销售额 const groupedMap = rawData.reduce((acc, curr) => { // 截取YYYY-MM格式年月 const yearMonth = curr.Order_Date.slice(0, 7); // 初始化年月分组,补全所有区域默认值0 if (!acc[yearMonth]) { acc[yearMonth] = { Order_Date: yearMonth }; allRegions.forEach(region => acc[yearMonth][region] = 0); } // 累加销售额,保留两位小数避免精度问题 acc[yearMonth][curr.Region] = Number((acc[yearMonth][curr.Region] + curr.Sales).toFixed(2)); return acc; }, {}); // 转换为目标数组格式 const result = Object.values(groupedMap); console.log(result);
输出说明
上述代码输出的result完全适配Nivo Bar Chart的数据要求:Order_Date作为X轴维度字段,East/South/Central作为不同系列的数值字段,无销售额的区域自动填充为0,数值统一保留两位小数符合统计规范。
内容的提问来源于stack exchange,提问作者faisal-akbar
相关产品推荐
相关产品推荐

