Search code examples
react-hooksreact-chartjs

Transferring data from a react hook to an array of objects


Encountered a problem when using react-charts. To draw a graph, you need an array of objects similar to the data:

data: [
  { "x": new Date("2020.03.18"), "y": 60 },
  { "x": new Date("2020.03.19"),"y": 23 },
  { "x": new Date("2020.03.20"),"y": 23 }
]

My data is stored in the react hook in this form: enter image description here

Here is my failed attempt to split a hook into an array of objects:

    const initialState = [
        dataCharts.map((units) => {
            {x: new Date(units.y), y: units.x}
        })
    ]

Solution

  • You can do something like this.

    dataCharts.map(d => {
      return {
        "x": d.x.split(" ")[0].split(".").reverse().join("."),
        "y": d.y
      }
    })