Chartjs-Display JSON data in react-chartjs-2

0👍

Would this work for you? A bit different approach on going through the data.

https://codesandbox.io/s/vigilant-faraday-4n1nb?file=/src/index.js

const constituencies = [
  { constituencyId: "1", name: "A" },
  { constituencyId: "2", name: "B" }
];
const candidates = [
  { candidateId: "1", lastName: "Person", firstName: "1" },
  { candidateId: "2", lastName: "Person", firstName: "2" }
];

const generateGraph = (data) => {
  let conArr = constituencies.map((con) => con.name);
  let canArr = constituencies.map((con, index) =>
    data
      .filter((entry) => entry.constituencyId === con.constituencyId)
      .map((entry) => {
        const candidate = candidates.find(
          (can) => can.candidateId === entry.candidateId
        );
        if (candidate === null) {
          return null;
        }
        return {
          label: candidate.lastName + ", " + candidate.firstName,
          data: new Array(index).fill(0).concat([entry.count])
        };
      })
  );

  const chartData = {
    labels: conArr,
    datasets: canArr
  };

  return chartData;
};

console.log(
  generateGraph([
    {
      candidateId: "1",
      constituencyId: "2",
      count: 50
    },
    {
      candidateId: "2",
      constituencyId: "2",
      count: 20
    }
  ])
);

Leave a comment