I have an array of objects called membership
:
[{name: 'Linus Pauling', address: '1805 Main Street', phone: '(615) 555-1010',
email: 'linus.pauling@gmail.com' },
{name: 'Maury Povich', address: '382 North Street', phone: '(423) 555-1997',
email: 'maury@themauryshow.org'}]
(Although only 4 are shown here, I really have ten key/value pairs per member.)
What is the best way to copy bits of this array to a range of cells in Google Sheets? I am trying to find a method to call the object values directly, and use the .SetValues method to copy them en masse, as opposed to one at a time.
To get all the members' names in column A, I've tried:
sheet.getRange(1,1,membership.length,1).setValues(membership[{member.name}]);
...which gives Missing : after property ID.
Or:
sheet.getRange(1,1,membership.length,1).setValues([membership[name]]);
...which gives ReferenceError: "name" is not defined.
Or:
sheet.getRange(1,1,membership.length,1).setValues([member.name]);
...which gives the "Cannot convert Array to Object[][]" error.
I apologize for the newbie question. I have seen answers about how to copy values from a multidimensional array to a sheet's range, but not an array of objects.
Are you looking to produce a table in the form:
etc?
If so, then the following snippet may help. The key thing to point out here is that you can't expect a given order when iterating through an object. i.e. Just because your representation of
membership
listsname
first, doesn't mean that if you were to use afor ... in
loop you could guarantee thatname
would come back first - Objects in JavaScript are unordered.To ensure a given order, the snippet I list defines an array
headings
in which you specify the order of the columns you want in the Sheet. This is used to guarantee the column order in the output:Output is :
See the script at the bottom of the Simple Mail Merge Tutorial for some useful code to retrieve data. Copy all the code from this comment down:
Once you have, the getRowsData returns not only the data, but a second item which is a list of the Headers. Using this, you can modfy the code from @Bardy to allow for the Headers in any order, and also other possible columns in between.
How about following script? This script is a container bound script of spreadsheet. There are 2 patterns. The arrangement of data is different for between pattern 1 and 2.
Pattern 1 is
Pattern 2 is
If my understanding for your questions was wrong, I apologize.