Skip to content

Instantly share code, notes, and snippets.

@kritollm
Last active September 19, 2016 21:11
Show Gist options
  • Save kritollm/7366cf6ea2347f47bce3e26b303f1875 to your computer and use it in GitHub Desktop.
Save kritollm/7366cf6ea2347f47bce3e26b303f1875 to your computer and use it in GitHub Desktop.
Convert array with flat objects to comma separated CSV. Also works with objects where prop(s) is an array with same length in all the objects.
var fs = require('fs');
function arrayToProps(o){
let props = Object.keys(o).forEach(p => {
if(o[p] instanceof Array){
var a = o[p];
delete o[p];
a.forEach((e, i) => (o[p + "_" + i] = e));
}
});
return o;
}
function convertToCsv(array, name) {
var hSplit = '","';
var stream = fs.createWriteStream('CSV/' + name + '_' + (new Date()).toDateString() + '_' + (Math.floor(Date.now() / (1000 * 60))) + '_pt.csv', { flags: 'a' });
array = array.map(e => arrayToProps(e));
var props = Object.keys(array[0]);
var header = '"' + props.join(hSplit) + '"\r\n'
stream.write(header);
array.forEach(e => stream.write('"' + props.map(p => e[p]).join(hSplit) + '"\r\n'));
stream.end();
}
let array = [
{name: 'test1', points: [3, 5, 6, 8, 9, 23, 44] },
{name: 'test2', points: [32, 51, 36, 18, 9, 23, 44] },
];
convertToCsv(array, "test"); // => "name","points_0","points_1","points_2","points_3","points_4","points_5","points_6"
// "test1","3","5","6","8","9","23","44"
// "test2","32","51","36","18","9","23","44"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment