1var colors = ["red", "blue", "green"];
2var colorsString = colors.join(","); //"red,blue,green"
1const arrayToCSV = (arr, delimiter = ',') =>
2 arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
1var objectToCSVRow = function(dataObject) {
2 var dataArray = new Array;
3 for (var o in dataObject) {
4 var innerValue = dataObject[o]===null?'':dataObject[o].toString();
5 var result = innerValue.replace(/"/g, '""');
6 result = '"' + result + '"';
7 dataArray.push(result);
8 }
9 return dataArray.join(' ') + '\r\n';
10}
11
12var exportToCSV = function(arrayOfObjects) {
13
14 if (!arrayOfObjects.length) {
15 return;
16 }
17
18 var csvContent = "data:text/csv;charset=utf-8,";
19
20 // headers
21 csvContent += objectToCSVRow(Object.keys(arrayOfObjects[0]));
22
23 arrayOfObjects.forEach(function(item){
24 csvContent += objectToCSVRow(item);
25 });
26
27 var encodedUri = encodeURI(csvContent);
28 var link = document.createElement("a");
29 link.setAttribute("href", encodedUri);
30 link.setAttribute("download", "customers.csv");
31 document.body.appendChild(link); // Required for FF
32 link.click();
33 document.body.removeChild(link);
34}
35