Skip to content

Instantly share code, notes, and snippets.

@chrisbolin
Created May 24, 2016 17:28
Show Gist options
  • Select an option

  • Save chrisbolin/0d9791d54648e4001fa46f6ff55663a6 to your computer and use it in GitHub Desktop.

Select an option

Save chrisbolin/0d9791d54648e4001fa46f6ff55663a6 to your computer and use it in GitHub Desktop.

Revisions

  1. chrisbolin created this gist May 24, 2016.
    18 changes: 18 additions & 0 deletions script.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    /*
    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];
    }