Converting an Array into an Object Array


This snippet helps you convert an array into an object array. Converting an array into an object array is useful when you need to export your Google Sheet's data to another application that only accepts json objects in its API requests. It's also just easier to work with data in an object array as opposed to a standard array since json objects have keys that can tell you exactly what the data values are for - unlike a standard array where it's all up to your ability to map the array positions.

With this convertArrayToObjectArray function, you'll need two parameters:

  • • The first one is the keys parameter which is basically the name you want to give for each field. Make sure these are in the same order as your data array. You can think of the keys as your column headers.
  • • The second is your data which will be the array. You'll want to make sure that it's a nested array. If you're pulling data out of a Google Sheet, it'll already be in a nested array format.


Here's an example of how running this function would look like:

convertArrayToObjectArray(["key1", "key2"], [["group1_value1", "group1_value2"], ["group2_value1", "group2_value2"]])

Let's go a bit further and look at an example where you've pulled data from a Google Sheet and want to convert it into an object array

const data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getDataRange().getValues() const dataHeaders = data[0] data.shift() // Array.shift() helps you remove the first position in your array const objectArray = convertArrayToObjectArray(dataHeaders, data) console.log(objectArray)

This example uses getDataRange() to get the Google Sheet's data. For other ways to get data, check out our Get Data from a Sheet how-to guide.

If you're trying to convert an Object Array into a flat array, check out our Converting an Object Array into a flat Array how-to guide.

thumbnail

NitroGAS Chrome Extension

Want to reference this code snippet right from your Google Apps Script Project? Check out our NitroGAS Chrome Extension. This tool will help you build your scripts faster than you could imagine. The tool itself and access to the code snippets are 100% FREE - Happy Coding!

Get the Extension