Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Created August 19, 2014 17:52
Show Gist options
  • Save mlconnor/8a6b4ab9134c1555e904 to your computer and use it in GitHub Desktop.
Save mlconnor/8a6b4ab9134c1555e904 to your computer and use it in GitHub Desktop.
converts and array of objects into a csv string
function arr2csv(arr) {
var cols = [];
/* get a list of unique columns */
_.each(arr, function(item) {
cols = _.union(_.keys(item), cols);
});
var csvRows = [cols.join("\t")];
for ( var i = 0; i < arr.length; i++ ) {
var row = arr[i];
var csvRow = [];
for ( var colI = 0; colI < cols.length; colI++ ) {
csvRow.push(_.has(row,cols[colI]) ? row[cols[colI]] : "");
}
csvRows.push(csvRow.join("\t"));
}
return csvRows.join("\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment