Pick Columns

You've turned rows into objects, and now you only need four of the twenty fields, in a set order, for an export, an email, or another tab. pickColumns(rows, headers) returns new objects with just those fields, in the order you list them. Missing fields come back as '' so every row has the same shape.

When to use

  • Building an export or report from a wide sheet
  • Sending only the fields a person or API should see
  • Lining up columns before writing rows to another tab

How to use this snippet

/** * Keep only the named fields of each row object, in the order given. * Missing fields become ''. * * @param {Object[]} rows row objects, e.g. from rowsToObjects * @param {string[]} headers field names to keep, in output order * @return {Object[]} */ function pickColumns(rows, headers) { return rows.map(function (row) { return headers.reduce(function (out, h) { out[h] = Object.prototype.hasOwnProperty.call(row, h) ? row[h] : ''; return out; }, {}); }); }

Example

function exportContacts() { var values = SpreadsheetApp.getActive().getSheetByName('CRM').getDataRange().getValues(); var rows = rowsToObjects(values); var headers = ['Name', 'Email', 'Company']; var slim = pickColumns(rows, headers); var out = [headers].concat(slim.map(function (r) { return headers.map(function (h) { return r[h]; }); })); SpreadsheetApp.getActive().getSheetByName('Export').getRange(1, 1, out.length, headers.length).setValues(out); }

Notes

  • Pairs with Rows To Objects And Back: read with rowsToObjects, pick, then write with objectsToRows.
  • Header names have to match exactly, including case and spaces.
  • It returns new objects. Your original rows aren't changed.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension