Created
August 25, 2022 05:12
-
-
Save Sidheeqpallam/6fa375592ef5e4d0e84e2d0ab955f77b to your computer and use it in GitHub Desktop.
convert an array of object to csv type data
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
const objectToCsv = function(data){ | |
const csvRows =[]; | |
//get the headers | |
const headers = Object.keys(data[0]); | |
csvRows.push(headers.join(',')); | |
//loop over the rows | |
for (const row of data){ | |
const values = headers.map(header =>{ | |
const escaped = (''+row[header]).replace(/"/g, '\\"') | |
return `"${escaped}"` | |
}) | |
csvRows.push(values.join(',')) | |
} | |
return csvRows.join('\n') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment