Skip to content

Instantly share code, notes, and snippets.

@anandsunderraman
Created September 23, 2019 20:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anandsunderraman/5f1f49dec3e4cbd4ad64e1b26e548658 to your computer and use it in GitHub Desktop.
Save anandsunderraman/5f1f49dec3e4cbd4ad64e1b26e548658 to your computer and use it in GitHub Desktop.
Robo 3T array to csv
//function to print CSV from an array for robomongo
//place this in .robomongorc.js which should be present in your home directory
//inspired by https://github.com/Studio3T/robomongo/wiki/How-to-export-to-CSV
function toCSV(array) {
let deliminator = ',';
let textQualifier = '\"';
let headers = [];
var data = {};
var count = -1;
for (var index in array[0]) {
if (headers.indexOf(index) == -1) {
headers.push(index);
}
}
for (var i = 0; i < array.length; i++) {
count++;
for (var index in array[i]) {
data[count + '_' + index] = array[i][index];
}
}
var line = '';
for (var index in headers) {
line += textQualifier + headers[index] + textQualifier + deliminator;
}
line = line.slice(0, -1);
print(line);
for (var i = 0; i < count + 1; i++) {
var line = '';
var cell = '';
for (var j = 0; j < headers.length; j++) {
cell = data[i + '_' + headers[j]];
if (cell == undefined) cell = '';
line += textQualifier + cell + textQualifier + deliminator;
}
line = line.slice(0, -1);
print(line);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment