-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
80 lines (61 loc) · 1.84 KB
/
index.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
76
77
78
79
80
var $ = require('./csv.js')
function parse_object(obj, path) {
if (path == undefined)
path = "";
var type = Object.prototype.toString.call(obj).replace('[object ','').replace(']','').toLowerCase();//$.type(obj);
var scalar = (type == "number" || type == "string" || type == "boolean" || type == "null");
if (type == "array" || type == "object") {
var d = {};
for (var i in obj) {
var newD = parse_object(obj[i], path + i + "/");
for(i in newD){
d[i] = newD[i];
}
}
return d;
}
else if (scalar) {
var d = {};
var endPath = path.substr(0, path.length-1);
d[endPath] = obj;
return d;
}
else return {};
}
function arrayFrom(json) {
var queue = [], next = json;
while (next !== undefined) {
if (Object.prototype.toString.call(next) == "[object Array]")
return next;
if (typeof(next) == "object")
for (var key in next)
queue.push(next[key]);
next = queue.shift();
}
return [json];
}
var doCSV = function (obj) {
var inArray = arrayFrom(obj.json);
var arr= [];
if(!!obj.thead){
inArray.map(function(v) {
var objArr={};
Object.keys(obj.thead).forEach(function(k){
objArr[obj.thead[k]] = v[k];
})
arr.push(objArr);
});
inArray = arr;
}
var id = document.getElementById(obj.id);
var fileName = !!obj.fileName ? obj.fileName : 'result';
var outArray = [];
for (var row in inArray){
outArray[outArray.length] = parse_object(inArray[row]);
}
var csv = $.csv.fromObjects(outArray);
var uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(csv);
id.setAttribute('href',uri);
id.setAttribute('download',fileName+'.csv');
}
module.exports = doCSV;