[Chartjs]-Dynamically pass the JSON data in chartjs

1👍

You can use reduce function to count for each category. working solution

let res = [...data].reduce(
(a, c) => (a[c.items.selectedItem] = (a[c.items.selectedItem] || 0) + 1, a),{});

Use the resulting object in your pie chart as following for labels and data.

labels = Object.keys(res);
data = Object.values(res));

0👍

I was a bit confused because you have both ‘truck’ & ‘trucks’, maybe thats an error in itself. But for your question, here is a solution:

  const a = data.filter((a) => a.items.selectedItem === "car");
  const b = data.filter((b) => b.items.selectedItem === "bikes");
  const c = data.filter((c) => c.items.selectedItem === "motor");
  const d = data.filter((d) => d.items.selectedItem === "truck");
  const e = data.filter((e) => e.items.selectedItem === "trucks");

And when you insert data into the pie:

<Pie
    data={{
      labels: ar,
      datasets: [
        {
          data: [a.length, b.length, c.length, d.length, e.length],
          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
        }
      }
    }}
  />

Leave a comment