function forLoopItems(data) {
for(let item in data) {
console.log(data[item])
}
}
// forLoopItems([1,2,3,4,5,6,7])
This code snippet helps you convert an array of objects into a flat array that you can use to import into a Google Sheet. This is pretty typical when you're importing data from an API response - see our Basic REST API GET Call Using JSON how-to guide for how to get data from an API using Google Apps Script.
Important Note: This snippet handles multiple objects that are structured into an Object Array. For a single object, please see our Converting JSON into a flat Array how-to guide.
To use this function, all you have to do is pass through the array of object into the function as a parameter. Like so:
convertObjectArrayToArray([{id:1,name:'test1'},{id:2,name:'test2'},{id:3,name:'test3'}])
Unlike converting a single object into a flat array, we'll make use of a loop to iterate through the object array. As we iterate through the object array, we'll push data into a separate array called finalArray
which will act as a the top level of our nested array.
In the first iteration, we'll use Object.keys()
to determine the column headers and push it into the first row of our nested array: finalArray.push()
.
For all other iterations in our loop, we'll first organize Object's values into its own array using array.push()
before pushing that entire array into the finalArray.
const finalArray = []
for(let item in objectArray) {
let object = objectArray[item]
if (item == 0) {
finalArray.push(Object.keys(object))
}
let array = []
for(let key in object) {
array.push(object[key])
}
finalArray.push(array)
}
Let's take this object array as an example,
[
{id:1,name:'test1'},
{id:2,name:'test2'},
{id:3,name:'test3'}
]
When we run it through the loop, we should expect to get an output with the column heads of id
and name
along with 3 rows of data:
[ [ 'id', 'name' ], [ 1, 'test1' ], [ 2, 'test2' ], [ 3, 'test3' ] ]
To go the other way around, where you convert a flat array into an object, check out our Converting an Array into an Object Array how-to guide.
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