-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
daniel
committed
Dec 22, 2019
1 parent
fe0aa8f
commit d2593d8
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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); |