Converting JSON into a flat Array


This code snippet helps you convert an object into a flat array that you can use to import into a Google Sheet.

Important Note: This snippet handles one object. For an array of objects, please see our Converting an Object Array into a flat Array how-to guide.

To use this function, all you have to do is pass through the object into the function as a parameter.

Let's take this object for example:

{name: 'test', country: 'USA', id: 123}

There are three object keys in this object: name, country, and id.

To convert it into an Array, we'll use the new Array() constructor which takes multiple parameters into it, but we'll only pass two parameters into it - one for the headers and one for the values.

You can grab the keys and values from your object by calling Object.keys() and Object.values(). Like so:

Object.keys(object) Object.values(object)

Using the object above as an example, we should expect to get this output:

[ [ 'name', 'country', 'id' ], [ 'test', 'USA', 123 ] ]

To run the function, you'll do this:

const object = {name: 'test', country: 'USA', id: 123} const result = convertJsonToArray(object) // Which is the same as running this: // const result = convertJsonToArray({name: 'test', country: 'USA', id: 123}) console.log(result)

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.

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