Created
June 21, 2022 22:24
-
-
Save alexyslozada/1a888f58320fcf27ad803740dd7e195b to your computer and use it in GitHub Desktop.
How to export / download data as text / csv file
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
// This data is a mock from your real data | |
const data = [{"name": "apple"}, {"name": "onion"}, {"name": "banana"}] | |
// We want to write this data into a string | |
const dataToString = data => { | |
let resp = "" | |
data.forEach(e => resp += e.name + "\n") | |
return resp | |
} | |
// Create the hidden link to download data | |
const downloader = data => { | |
const hiddenElement = document.createElement('a') | |
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(data) | |
hiddenElement.target = '_blank' | |
hiddenElement.download = 'MyDownload.csv' | |
hiddenElement.click() | |
} | |
const download = () => { | |
const csv = dataToString(data) | |
downloader(csv) | |
} | |
download() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment