Search code examples
javascriptarraysobjectunix-timestamp

react-stockcharts with Json object


Hello guys I am trying to implement React-stockchart into my project however i am running into an issue that i have been facing since few days now with the data that i need to pass to the chart.

React-stockchart accept Data in this format

 Data=[
    0:{
       open:25.436282332605284 , 
       high:25.835021381744056 , 
       low: 25.411360259406774,
       date:Date 2010-01-03T23:00:00.000Z,
       volume:38409100},
    1:{....}
    2:{....}
]

Using this function i was able to convert my entry data from this format My data to this format

the function that i use to convert the data into a similair format that React-Stockchart accept:

convertData(data) {
      var keys = ["date","open","close","hight","low","volume"],
          i = 0, k = 0,
          obj = null,
          output = [];
      for (i = 0; i < data.length; i++) {
          obj = {};
          for (k = 0; k < keys.length; k++) {
              obj[keys[k]] = data[i][k];
          }
      output.push(obj);
      }
    return output;
  }

after using this function i got a result in this format , however the date is in unix timestamp and i am looking for a way to implement into my function to get the date into a similair format that React-stockchart accept

Data=[
        0:{
           open:10608 , 
           high:10617 , 
           low: 10613.07326842,
           date:1519288380000,
           volume:25.33908407},
        1:{....}
        2:{....}
    ]

Solution

  • You can create a new Date object with the timestamp:

    var dateObj = new Date(timestamp);
    

    so in your situation:

    convertData(data) {
          var keys = ["date","open","close","hight","low","volume"],
              i = 0, k = 0,
              obj = null,
              output = [];
          for (i = 0; i < data.length; i++) {
              obj = {};
              obj[keys[0]] = new Date(data[i][0]); 
              for (k = 1; k < keys.length; k++) {
                  obj[keys[k]] = data[i][k];
              }
          output.push(obj);
          }
        return output;
      }