skip to Main Content

I need to retrieve some data from a Google Spreadsheet via App Script for which I set up a DoGet function. Currently I´m retrieving an array but a I need data comes as JSON key-value pairs format.

The table on Google Sheets looks like this:

description

the DoGet function is set up like this:


function doGet(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 

  var returnData = sheet.getRange('A1:B2').getValues()

return ContentService.createTextOutput(JSON.stringify(returnData))
}

I´m retriving this:

[
    ["fruit", "vegetable"],
    ["ABC", "DEF"]
]

I need to retrieve JSON key:value pairs like this:

{
"fruit": "ABC",
"vegetable": "DEF"
}

2

Answers


  1. The problem is that you are extracting a value from a Google Sheet, so this response is how your data is represented on your sheet.

    [
        ["fruit", "vegetable"],
        ["ABC", "DEF"]
    ]
    

    You can obviously map your data in order to get the response that you want.

    const arrayData = [
        ["fruit", "vegetable"],
        ["ABC", "DEF"]
    ];
    
    const resultObject = arrayData[0].reduce((acc, key, index) => {
        acc[key] = arrayData[1][index];
        return acc;
    }, {});
    
    console.log(resultObject);

    but this comes with a problem, what if you have more rows, how would you handle it then?

    Login or Signup to reply.
  2. You can leverage on Array:slice and Array:map functions in and accomplish your expected output.

    Refer the below code :

    const nestedArray = [
      ["fruit", "vegetable"],
      ["ABC", "DEF"],
      ["CC", "DDD"],
      ["FF", "GG"],
      ["FF2", "G3G"]
    ];
    
    function arrTranformer(arr) {
      let transformedArray = arr.slice(1).map(innerArray => {
        let obj = {};
        if (innerArray.length >= 2) {
          obj[arr[0][0]] = innerArray[0];
          obj[arr[0][1]] = innerArray[1];
        }
        return obj;
      });
    
      return transformedArray;
    }
    
    console.log(JSON.stringify(arrTranformer(nestedArray)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search