I'm not a JavaScript dev, and would like some pointers as to how I can convert an array of objects (acquired from a WebAPI call), into arrays suitable for Chart.JS.
My code so far (which works) looks like this:
<canvas id="line-chart" width="800" height="450"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<script>
// webapi call returns an object which looks like this
var raw = {
message: "Success: 3 entries",
didError: false,
errorMessage: null,
model:
[
{ time: "2019-09-26T13:19:00", value1: 1, value2: 2, value3: 3, value4: 4 },
{ time: "2019-09-26T13:20:00", value1: 22, value2: 21, value3: 20, value4: 19 },
{ time: "2019-09-26T13:21:00", value1: 10, value2: 20, value3: 40, value4: 70 }
]
};
// chart.js needs the data to look like this
var data = {
labels: ["19:00", "20:00", "20:01"],
datasets: [
{
data: [1, 22, 10],
label: "Value 1",
borderColor: "red",
fill: false
},
{
data: [2, 21, 20],
label: "Value 2",
borderColor: "blue",
fill: false
},
{
data: [3, 20, 40],
label: "Value 3",
borderColor: "green",
fill: false
},
{
data: [4, 19, 70],
label: "Value 4",
borderColor: "orange",
fill: false
}
]
};
var options = { title: { display: true, text: 'stuff' } };
var chart = new Chart(document.getElementById("line-chart"), { type: 'line', data: data, options: options });
</script>
How do I turn my "raw" data into the format that Chart.JS is expecting ? I can make the webAPI (which I wrote) return anything, but didn't think returning chart.js format arrays was the way to go. It currently returns 1440 objects - not 3 !
I don't know js, so I don't know how to do loops and type conversions, so any pointers gratefully received. If possible, I would rather not include extra packages.
map, for example,raw.model.map( x => x.value1 )would give you[1, 22, 10].map( x => x.value1)is shorthand for.map( function(x) { return x.value1; }... support is pretty broad now: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…