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.
