-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport-data.js
75 lines (57 loc) · 1.75 KB
/
export-data.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const downloadAsFile = require('download-as-file')
function exportData(card) {
let series = []
let labels = {}
//if Card
if(card.series != undefined) {
series = card.series
labels = card.options.xaxis.categories
}
//if Chart
if(card.data != undefined) {
series = card.data.datasets
labels = card.data.labels
}
if(series.length == false) return false
if(labels.length == false) return false
if(series[0].data == undefined) return false
let toDashCase = function(str) {
return (' ' + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => {
return '-' + chr}).substring(1);
}
let toCSV = function(array) {
return array.map(row => row.join(',')).join('\n')
}
let csvArray = []
csvArray[0] = []
//top left
csvArray[0][0] = "label\\series";
//fill left column
for (let i = 0; i < labels.length; i++) {
csvArray[i+1] = [] //init
csvArray[i+1][0] = labels[i];
}
//each serie
for(const[serieKey, serie] of Object.entries(series)) {
csvArray[0].push(serie.label); //add title to head
let i = 0 //if the data is an Object and not Array
for(const[dataKey, value] of Object.entries(serie.data)) {
csvArray[i+1].push(value)
i++
}
}
let csv = toCSV(csvArray)
let fileName = 'chart-export.csv'
if(card.uriKey != undefined && card.uriKey != false) {
fileName = card.uriKey + '.csv'
} else {
if(card.title != undefined && card.title != false) {
fileName = toDashCase(card.title) + '.csv'
}
}
downloadAsFile({
data: csv,
filename: fileName
})
}
module.exports = exportData;