Как я могу разделить этот объект.значения с общей суммой?

#javascript #reactjs #chart.js #react-chartjs

Вопрос:

У меня есть это, где car 2 и total 12. Поэтому я хотел получить процент от этого, но это в Object.values(res)

Я хотел, чтобы набор данных на графике был в процентах. Допустим car , равно 2, а total число равно 12. Так и должно быть 16.66% . Однако в моем наборе данных прямо сейчас он показывает только 2.

Это ссылка на codesandbox : https://codesandbox.io/s/bar-graph-9nr8u?file=/src/App.js:0-3062

 export default function App() {
  const data = [
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: false,
        type1: true,
        selectedItem: "car"
      },
      displayName: "Person1"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "bikes"
      },
      displayName: "Person2"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "car"
      },
      displayName: "Person3"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "motor"
      },
      displayName: "Person4"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "motor"
      },
      displayName: "Person5"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "truck"
      },
      displayName: "Person6"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "bikes"
      },
      displayName: "Person7"
    },
    {
      birthdate: "Thu Aug 31 2000",
      createdDate: { seconds: 1630377545, nanoseconds: 313000000 },
      items: {
        type2: true,
        type1: true,
        selectedItem: "truck"
      },
      displayName: "Person8"
    }
  ];

  const total = 12;

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

  const rounded = Object.entries(res).reduce((acc, [key, value]) => {
    return { ...acc, [key]: value.toFixed(2) };
  }, {});

  return (
    <div className="App">
      <Pie
        data={{
          labels: Object.keys(rounded),
          datasets: [
            {
              data: Object.values(rounded),
              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
            }
          }
        }}
      />
    </div>
  );
}
 

Комментарии:

1. Эй, не могли бы вы поподробнее рассказать о том, чего вы пытаетесь достичь, это неясно, так что помочь трудно, спасибо!

2. @TheBritishAreComing здравствуйте, я обновил пост. Спасибо

3. Откуда это 12 берется?

4. @mplungjan const total = 12; это был всего лишь образец данных

Ответ №1:

Ты имеешь в виду

[key]: ((value/total)*100).toFixed(2)

 const data = [{
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: false,
      type1: true,
      selectedItem: "car"
    },
    displayName: "Person1"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "bikes"
    },
    displayName: "Person2"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "car"
    },
    displayName: "Person3"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "motor"
    },
    displayName: "Person4"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "motor"
    },
    displayName: "Person5"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "truck"
    },
    displayName: "Person6"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "bikes"
    },
    displayName: "Person7"
  },
  {
    birthdate: "Thu Aug 31 2000",
    createdDate: {
      seconds: 1630377545,
      nanoseconds: 313000000
    },
    items: {
      type2: true,
      type1: true,
      selectedItem: "truck"
    },
    displayName: "Person8"
  }
];

const total = 12;

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

const rounded = Object.entries(res).reduce((acc, [key, value]) => {
  return { ...acc,
    [key]: ((value/total)*100).toFixed(2)
  };
}, {});

console.log(rounded)
console.log(res) 

Ответ №2:

Вы можете увидеть свой измененный код и поле здесь: https://codesandbox.io/s/bar-graph-forked-vp4uk В этом случае вы должны использовать процент вместо значения.

Итак, вы должны измениться:

   const rounded = Object.entries(res).reduce((acc, [key, value]) => {
    return { ...acc, [key]: value.toFixed(2) };
  }, {});
 

к этому:

   const rounded = Object.entries(res).reduce((acc, [key, value]) => {
    return { ...acc, [key]: ((value / total) * 100).toFixed(2) };
  }, {});