Search code examples
javascriptjsonreactjsvictory-charts

make a list of dictionnary in javascript from a json


I have a list of dictionnaries i get from my API:

i can get the data as json this way :

[{"2020-03-11 14:00:00":10.765736766809729}
,{"2020-03-11 15:00:00":10.788090128755387},
{"2020-03-11 16:00:00":10.70594897472582},
{"2020-03-11 17:00:00":10.435443490700994},
{"2020-03-11 18:00:00":9.748152122079162},
{"2020-03-11 19:00:00":9.541845493562244},
{"2020-03-11 20:00:00":10.161242250834528}]

Or i can also get it this way :

{"date":{"0":"2020-03-11 14:00:00","1":"2020-03-11 15:00:00","2":"2020-03-11 16:00:00","3":"2020-03-11 17:00:00","4":"2020-03-11 18:00:00","5":"2020-03-11 19:00:00","6":"2020-03-11 20:00:00","7":"2020-03-11 21:00:00","8":"2020-03-11 22:00:00","9":"2020-03-11 23:00:00","10":"2020-03-12 00:00:00"},
"availability":{"0":10.7657367668,"1":10.7880901288,"2":10.7059489747,"3":10.4354434907,"4":9.7481521221,"5":9.5418454936,"6":10.1612422508,"7":10.8490701001,"8":11.0297448736,"9":10.9386623748,"10":11.2957796853}}"

For a victory chart in my react app, i need the list to be that way :

[
{x : new Date("2020-03-11 14:00:00"),y: 10.765736766809729},
{x : new Date("2020-03-11 15:00:00"),y: 10.788090128755387},
{x : new Date("2020-03-11 16:00:00"),y: 10.70594897472582},
{x : new Date("2020-03-11 17:00:00"),y: 10.435443490700994},
{x : new Date("2020-03-11 18:00:00"),y: 9.748152122079162},
{x : new Date("2020-03-11 19:00:00"),y: 9.541845493562244},
{x : new Date("2020-03-11 20:00:00"),y: 10.161242250834528}
]

I am a quite a noob in javascript. Any observation or suggestion would be appreciated.


Solution

  • You can map the data to new object matching the structure you need.

    const data = [
      {"2020-03-11 14:00:00":10.765736766809729},
      {"2020-03-11 15:00:00":10.788090128755387},
      {"2020-03-11 16:00:00":10.70594897472582},
      {"2020-03-11 17:00:00":10.435443490700994},
      {"2020-03-11 18:00:00":9.748152122079162},
      {"2020-03-11 19:00:00":9.541845493562244},
      {"2020-03-11 20:00:00":10.161242250834528}]
      
      var chartData = data.map(item => { 
        for (const key in item)
          return { x: new Date(key), y: item[key] }
      })`