Creating a JSON object from Google Sheets

前端 未结 2 1732
傲寒
傲寒 2020-12-16 02:39

I am trying to learn AppScript and I am using Google Sheets as an example. I want to create a simple JSON object using some data populated in the Sheet.

Table Exampl

2条回答
  •  無奈伤痛
    2020-12-16 03:25

    I know it's been a while, but I came up with a slightly more flexible solution. I've created an aptly named function that converts spreadsheet data to objects, given a set of headers and a set of rows.

    function convertToObjects(headers, rows)
    {
      return rows.reduce((ctx, row) => {
        ctx.objects.push(ctx.headers.reduce((item, header, index) => {
          item[header] = row[index];
          return item;
        }, {}));
        return ctx;
      }, { objects: [], headers}).objects;
    }
    

    You can call the above function like this:

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YourSheetName');
    var [headers, ...rows] = sheet.getDataRange().getValues();
    var objects = convertToObjects(headers, rows);
    

    If you need to ignore the first row and get headers from the second row (like I do), then you can do this instead:

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YourSheetName');
    var [_, headers, ...rows] = sheet.getDataRange().getValues();
    var objects = convertToObjects(headers, rows);
    

    If you have any improvements to this, please let me know in the comments below.

提交回复
热议问题