I have a CSV file named data.csv with the following content:
data.csv:
time,voltage
0.0,20
0.2,1
0.3,15
0.4,2
0.5,31
0.6,11
I want to create a JavaScript data structure from this CSV data and store it in a variable. The desired data structure should look like this:
Desired Data Structure:
[
{ x: 0.0, y: 20 },
{ x: 0.2, y: 1 },
{ x: 0.3, y: 15 },
{ x: 0.4, y: 2 },
{ x: 0.5, y: 31 },
{ x: 0.6, y: 11 }
]
How can I achieve this in JavaScript?
I specifically need this data structure for creating a chart using the chart.js library. If anyone has experience or examples with parsing CSV data into a suitable format for chart.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="chart" width="1920" height="1080"></canvas>
<script>
const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
yAxisID: 'yA',
label: 'Temperature',
data: [
{ x: 0.05, y: 12 },
{ x: 0.15, y: 19 },
{ x: 0.25, y: 3 },
{ x: 0.35, y: 5 },
{ x: 0.45, y: 2 },
{ x: 0.55, y: 3 },
],
},
{
yAxisID: 'yB',
label: 'Voltage',
data: [
{ x: 0.0, y: 20 },
{ x: 0.2, y: 1 },
{ x: 0.3, y: 15 },
{ x: 0.4, y: 2 },
{ x: 0.5, y: 31 },
{ x: 0.6, y: 11 },
],
}
]
},
options: {
responsive: true,
scales: {
yA: {
type: 'linear',
position: 'left',
ticks: { beginAtZero: true, color: 'blue' },
grid: { display: false },
borderWidth: 1,
pointStyle: 'circle',
//backgroundColor: 'blue',
borderColor: 'blue',
tension: 0,
},
yB: {
type: 'linear',
position: 'left',
ticks: { beginAtZero: true, color: 'green' },
grid: { display: false },
borderWidth: 1,
pointStyle: 'circle',
//backgroundColor: 'green',
borderColor: 'green',
tension: 0,
},
x: {
ticks: { beginAtZero: true },
type: 'linear',
}
}
}
});
</script>
</body>
</html>



