You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chart.js饼图中动态传入JSON数据中各selectedItem对应的用户总数?

解决方法

咱们可以分三步完成需求:先统计每个selectedItem对应的用户数量,再把统计结果转换成饼图需要的格式,最后替换到饼图组件里。具体实现如下:

1. 统计selectedItem的用户总数

用JavaScript的Array.reduce()方法就能高效完成统计,另外注意到你的数据里有truck(Person8)和trucks(Person6)两个相似选项,我默认把它们合并为trucks,如果不需要合并可以删掉对应的判断逻辑:

// 遍历数据,统计每个选项的用户数
const countItems = data.reduce((acc, current) => {
  // 可选:统一truck和trucks的命名
  const selected = current.items.selectedItem === 'truck' ? 'trucks' : current.items.selectedItem;
  // 累加对应选项的数量
  acc[selected] = (acc[selected] || 0) + 1;
  return acc;
}, {});

执行这段代码后,countItems会得到这样的结果:

{ car: 2, bikes: 2, motor: 2, trucks: 2 }

2. 转换为饼图适配的格式

把统计后的对象拆分成饼图需要的labels(标签)和data(数值)数组:

// 提取所有选项作为饼图标签
const pieLabels = Object.keys(countItems);
// 提取对应选项的用户数量作为饼图数据
const pieData = Object.values(countItems);

3. 更新饼图组件

把上面生成的pieLabels和pieData替换到你的<Pie>组件配置中即可:

<Pie
  data={{
    labels: pieLabels, // 替换为动态生成的标签
    datasets: [
      {
        data: pieData, // 替换为统计后的用户数量
        backgroundColor: ["red", "yellow", "green", "blue", "pink"],
        borderColor: ["rgba(255, 99, 132, 1)"],
        borderWidth: 1
      }
    ]
  }}
  height={400}
  width={600}
  options={{
    maintainAspectRatio: false,
    title: { display: true, text: "Selected", fontSize: 20 },
    legend: { labels: { fontSize: 25 } }
  }}
/>

完整整合示例

把所有代码整合到你的组件里,大概是这样的:

import { Pie } from 'react-chartjs-2';

const YourChartComponent = () => {
  const data = [
    // 你的原始JSON数据...
  ];

  // 统计用户选择的各选项数量
  const countItems = data.reduce((acc, current) => {
    const selected = current.items.selectedItem === 'truck' ? 'trucks' : current.items.selectedItem;
    acc[selected] = (acc[selected] || 0) + 1;
    return acc;
  }, {});

  const pieLabels = Object.keys(countItems);
  const pieData = Object.values(countItems);

  return (
    <Pie
      data={{
        labels: pieLabels,
        datasets: [
          {
            data: pieData,
            backgroundColor: ["red", "yellow", "green", "blue", "pink"],
            borderColor: ["rgba(255, 99, 132, 1)"],
            borderWidth: 1
          }
        ]
      }}
      height={400}
      width={600}
      options={{
        maintainAspectRatio: false,
        title: { display: true, text: "Selected", fontSize: 20 },
        legend: { labels: { fontSize: 25 } }
      }}
    />
  );
};

export default YourChartComponent;

这样饼图就会根据实际的用户选择数据动态展示各选项的人数占比了。如果不需要合并truck和trucks,只需要删除reduce里的命名统一逻辑即可。

内容的提问来源于stack exchange,提问作者JS3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:27:34