Skip to content

Instantly share code, notes, and snippets.

@thc282
Last active July 18, 2024 10:02
Show Gist options
  • Save thc282/92b698dea3a01893f669529125881500 to your computer and use it in GitHub Desktop.
Save thc282/92b698dea3a01893f669529125881500 to your computer and use it in GitHub Desktop.
Convert Json to CSV format & popout form
//Convert to csv
downloadCSVFromJson = (filename, arrayOfJson) => {
// convert JSON to CSV
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(arrayOfJson[0])
let csv = arrayOfJson.map(row => header.map(fieldName =>
JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
// Create link and download
var link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv));
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
//Form hide
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
var forms = document.getElementsByClassName('modal');
var Currform;
for (let form of forms) {
if(form.style.display == 'block')
Currform = form;
}
if(event.target == Currform){
Currform.style.display = "none";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment