-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoCsv.js
76 lines (68 loc) · 1.6 KB
/
toCsv.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
function toCsv(list){
var toIsoDateString = function(date){
var pad = function(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
};
return date.getUTCFullYear()
+ '-' + pad( date.getUTCMonth() + 1 )
+ '-' + pad( date.getUTCDate() )
+ 'T' + pad( date.getUTCHours() )
+ ':' + pad( date.getUTCMinutes() )
+ ':' + pad( date.getUTCSeconds() )
+ '.' + String( (date.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
var lines = [];
var getHeader = function(prefix, item){
var header = [];
var addHeader = function(key){
if (prefix){
header.push(prefix + "." + key);
} else {
header.push(key);
}
};
for(var key in item){
if (!item.hasOwnProperty(key)){
continue;
}
if (item[key] instanceof Date){
addHeader(key);
} else if (typeof item[key] === 'object'){
header.push(getHeader(key, item[key]));
} else {
addHeader(key);
}
}
return header.join();
};
var getRow = function(item){
var values = [];
for(var key in item){
if (!item.hasOwnProperty(key)){
continue;
}
if (item[key] instanceof Date){
values.push(toIsoDateString(item[key]));
} else if (typeof(item[key]) === 'object'){
values.push(getRow(item[key]));
} else {
values.push(item[key]);
}
}
return values.join();
};
var headerPrinted = false;
list.forEach(function(item){
if(!headerPrinted){
lines.push(getHeader("", item));
headerPrinted = true;
}
lines.push(getRow(item));
});
return lines.join('\n');
}