Skip to content

React how to create a data for chart?

I have a line chart react-google-charts. This chart accepts the data in the form of:

const data = [
        ["Date", "Realizado"],
        ["Jan 01", 4 ],
        ["Jan 07", 12],
        ["Jan 14", 20],
        ["Jan 28", 282],
      ];

And I get data from API. This data returns;

(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
  0: {period: '2021/09', value: 0.9256896545996849}
  1: {period: '2021/06', value: 0.9754303727212889}
  2: {period: '2021/03', value: 0.9791388246940228}
  3: {period: '2020/12', value: 1.015357654499295}
  4: {period: '2020/09', value: 0.9337976106510073}
  5: {period: '2020/06', value: 0.9930550362681277}
  6: {period: '2020/03', value: 1.064082963594007}
  7: {period: '2019/12', value: 1.095682769989701}
length: 8
[[Prototype]]: Array(0)

How can I fit this array as chart data?

Answer

Something like this may work:

const chartData = apiData.map(obj => [obj.preriod, obj.value])

PS. you may need to reformat your date