Last active
September 19, 2016 21:11
-
-
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.
This file contains hidden or 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
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