Skip to content

Instantly share code, notes, and snippets.

@chrisbolin
Created May 24, 2016 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbolin/0d9791d54648e4001fa46f6ff55663a6 to your computer and use it in GitHub Desktop.
Save chrisbolin/0d9791d54648e4001fa46f6ff55663a6 to your computer and use it in GitHub Desktop.
Documents -> Spreadsheet Array
/*
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