I am trying to convert a JavaScript object set in to CSV format
You can get the idea about my Javascript object, if you put it in online JSON parser http://json.pars
This is a quick & dirty, but probably works for most cases:
const headers = Object.keys(objAry[0])
console.log(headers.join())
objAry.forEach(r => console.log(
Object.values(r)
.map(c => Array.isArray(c)? `"${c.join()}"` : c)
.join())
)
Below code will convert and download JSON array to csv as a file.
function exportJSONToCSV(objArray) {
var arr = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
var str =
`${Object.keys(arr[0])
.map((value) => `"${value}"`)
.join(',')}` + '\r\n';
var csvContent = arr.reduce((st, next) => {
st +=
`${Object.values(next)
.map((value) => `"${value}"`)
.join(',')}` + '\r\n';
return st;
}, str);
var element = document.createElement('a');
element.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
element.target = '_blank';
element.download = 'export.csv';
element.click();
}
Here's a solution similar to mightybruno's answer that handles strings containing commas. None of the other answers seem to take this in to consideration.
function objectsToCSV(arr) {
const array = [Object.keys(arr[0])].concat(arr)
return array.map(row => {
return Object.values(row).map(value => {
return typeof value === 'string' ? JSON.stringify(value) : value
}).toString()
}).join('\n')
}