Converting Google Sheets cell values to an object array with heading keys using Google Apps Script

This is a sample script for converting the values of Google Spreadsheet to an object using Google Apps Script.

I have a minor obsession with methods for converting Google Sheets data to an object array. Over the years I’ve documented various approaches I’ve developed on my personal site, like this one, but this solution from Kanshi Tanaike has to be my new favourite:

function myFunction() {
  const sheetName = "Sheet1";
  const [headers, ...rows] = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName(sheetName)
    .getDataRange()
    .getValues();
  const res = rows.map((r) =>
    headers.reduce((o, h, j) => Object.assign(o, { [h]: r[j] }), {})
  );
  console.log(res);
}

Source: Converting Values of Google Spreadsheet to Object using Google Apps Script

2 comments for “Converting Google Sheets cell values to an object array with heading keys using Google Apps Script”

  1. kapil

    very very heplfull
    but is there a way we can create following type array from the sheet data where the each hoby coms from different column

    object ( {
    name: ‘John’,
    age: 20,
    hobbies: [‘reading’, ‘games’, ‘coding’],},
    }

Leave a Reply

Your email address will not be published. Required fields are marked *