Created
May 24, 2016 17:28
-
-
Save chrisbolin/0d9791d54648e4001fa46f6ff55663a6 to your computer and use it in GitHub Desktop.
Documents -> Spreadsheet Array
This file contains 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
/* | |
converts an array of objects into an array of row arrays, | |
suitable for use in e.g. a csv coversion (npm install csv-stringify) | |
includes the header row. | |
e.g. | |
objectArray = [{a: 1, b: 120}, {a: 2, c: 'horse'}] | |
toRows(objectArray) -> [ ['a', 'b', 'c'], [1, 120, undefined], [2, undefined, 'horse'] ] | |
*/ | |
const toRows = objectArray => { | |
const names = lodash | |
.union.apply(lodash, objectArray.map(row => lodash.keys(row))) | |
.sort(); | |
const rows = objectArray.map(obj => ( | |
names.map(name => obj[name]) | |
)); | |
return [names, ...rows]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment