Darren Darren - 8 months ago 80
jQuery Question

JSON data to valid data array in JS

I need to alter my JSON API from https://demo.piwik.org/?module=API&method=VisitsSummary.getVisits&idSite=7&period=day&date=last3&format=json&token_auth=anonymous

{"2017-12-21":767,"2017-12-22":571,"2017-12-23":31}


to a valid array for my charts in NVD3.js as

[ { "key" : "Page Visits" , "values" : [ [ 1025409600000 , 767] , [ 1028088000000 , 571] , [ 1030766400000 , 31] }]


NOTE: These dates do not match the
JSON
and
Array
but highlight the conversion needed, if anyone can explain to me the date format used in NVD3.js that would be great too.

If helpful, I can add the scripts used to
get
data and display the NVD3 Chart.

Answer Source

You can use array#map to convert your object to array. Then use [ { "key" : "Page Visits" , "values" : result }]; to get the required object.

var data = {"2017-12-21":767,"2017-12-22":571,"2017-12-23":31};
var result = Object.keys(data).map(k => [new Date(k).getTime(), data[k]]);
console.log(result);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download