2

I am wring a website using Node.Js. I got data from calling some API and returns to me JSON array in this format:

[{ '2015-04-08T17:12:05+00:00': 103.7 },{ '2015-04-08T17:13:05+00:00': 109.5 },{ '2015-04-08T17:14:05+00:00': 106 },{ '2015-04-08T17:15:05+00:00': 112.6 }]

So I want to use vis.js library to display this data like this:

vis example

Please correct me if I am wrong. I think vis.js only accepts dataset in this format:

[{x: '2014-06-11', y: 10},{x: '2014-06-12', y: 25},{x: '2014-06-13', y: 30},{x: '2014-06-14', y: 10}]
  1. converting json array format.

  2. directly feeding the raw data to vis.js.

Don't know how to do it.
Thank you in advance!!!

Community
  • 1
  • 1
Emma
  • 57
  • 1
  • 6

1 Answers1

1

This will permute your array to make it match your specs :

var dataBefore = [{ '2015-04-08T17:12:05+00:00': 103.7 },{ '2015-04-08T17:13:05+00:00': 109.5 },{ '2015-04-08T17:14:05+00:00': 106 },{ '2015-04-08T17:15:05+00:00': 112.6 }];

var dataAfter = [];

for(var i = 0; i < dataBefore.length; i++) {
  var item = dataBefore[i];
  for(date in item) {
    dataAfter.push({x: date, y: item[date]});
  }
}

console.log(dataAfter);


//added below for display the output
$(".results").append(JSON.stringify(dataAfter));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results">
</div>
Jeff Sloyer
  • 4,899
  • 1
  • 24
  • 48
Tristan Foureur
  • 1,647
  • 10
  • 23
  • A small addition: `var cleanDate = date.slice(0,10); dataAfter.push({x: cleanDate, y: item[date]});` to output the date format requested. – andybeli Apr 10 '15 at 17:07