-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv.js
68 lines (59 loc) · 1.38 KB
/
csv.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
const data1 = [
{
"name": "John",
"type": "dog"
},
{
"name": "Sparky",
"type": "dog"
},
{
"name": "Nova",
"type": "cat"
},
{
"name": "Manuel",
"type": "dog"
},
{
"name": "Caesar",
"type": "cat"
},
{
"name": "Gill",
"type": "fish"
}
];
const generateCsvData = (ar) => {
return ar.reduce((acc, el) => {
if (acc.length === 0) {
acc.push(Object.keys(el).map(head => head.toUpperCase()));
}
acc.push(Object.values(el));
return acc;
}, [])
}
const generateCsvFile = (ar) => {
let content = '';
ar.forEach(line => {
content += line.join(',') + '\n';
});
return content;
}
function download(filename, text) {
if (typeof document === 'undefined') {
console.log('this function can be run only in browser');
return;
}
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
const array2Data = generateCsvData(data1);
const content = generateCsvFile(array2Data);
download('mycontent', content);
console.log(content);