reactjs 格式化数据以在recharts React中构建堆叠柱

nbnkbykc  于 2022-12-03  发布在  React
关注(0)|答案(1)|浏览(131)

我的问题是以最好的方式格式化接收到的数据来构建一个自定义的recharts堆叠条形图。
我需要按group_by字段和每个Xaxis键(usage_date 字段)格式化数据,以图像上的方式显示数据:

尝试了很多方法,但突然都失败了。
需要为一个X轴(usage_date 字段)设置格式的数据示例:

{
    "group_by": "Amazon Route 53",
    "usage_date": "2022-09-01",
    "account_id": "111",
    "service_name": "Amazon Route 53",
    "total_cost": 0.50038,
    "total_usage_quantity": 111,
    "resource_name": "",
    "resource_id": ""
},
{
    "group_by": "AWS Key Management Service",
    "usage_date": "2022-09-01",
    "account_id": "111",
    "service_name": "Amazon Route 53",
    "total_cost": 0.50038,
    "total_usage_quantity": 111,
    "resource_name": "",
    "resource_id": ""
},
{
    "group_by": "AWS Support [Business]",
    "usage_date": "2022-09-01",
    "account_id": "111",
    "service_name": "Amazon Route 53",
    "total_cost": 0.50038,
    "total_usage_quantity": 111,
    "resource_name": "",
    "resource_id": ""
},
{
    "group_by": "AWS Secrets Manager",
    "usage_date": "2022-09-01",
    "account_id": "111",
    "service_name": "Amazon Route 53",
    "total_cost": 0.50038,
    "total_usage_quantity": 111,
    "resource_name": "",
    "resource_id": ""
}

BarChart的React代码:

<ResponsiveContainer width="100%" height={500}>
  <BarChart data={barChartData} barCategoryGap="28%">
    <CartesianGrid strokeDasharray="3 3" strokeOpacity={0.3} />
      <XAxis fontSize={11} />
      <YAxis fontSize={11} />
      <Tooltip />
  </BarChart>
</ResponsiveContainer>

感谢大家提供的任何帮助!

7uhlpewt

7uhlpewt1#

一个简洁的方法是:

const groupBy = (data) => {
  return _.chain(data)
    .groupBy("group_by")
    .map((value, key) => ({
      key: key,
      usage_date: value[0].usage_date,
      total_cost: _.sumBy(value, "total_cost"),
    }))
    .value();
};

相关问题