Perhaps the easiest way to assign a default value to a variable is to append the ||
conditional after referencing the variable.
For example, after looping through an array and mapping the values to properties within an object, I needed to test whether the property had been assigned.
As I use Google Spreadsheets to iterate through data imagine the following data set:
A | B | C | |
---|---|---|---|
1 | Name | Age | Choice |
2 | Ryan | 50 | A |
3 | Sara | 27 | |
4 | Jude | 29 | C |
Data set containing rows of data, except for one row with a blank “Choice” value.
Upon grabbing this data in Google App Script using a quick one liner:
|
|
We now have our sheet data wrapped into a 2-dimensional array.
If we now reduce
this array into an object such that we can easily reference each element within the data
variable we should easily be able to do like:
|
|
Hopefully the above code is somewhat self-explanatory, but here we only have one condition and that is to remove our header row in our data and then mapped all elements within our array to a property – in essence corresponding to the header titles.
However, upon doing our data manipulation we’d now like to return it back to the sheet and therefore need to map
it back to a 2-dimensional array. Here’s how that code would look:
|
|
This may appear to look great, but if we were to inspect the arr2d
variable we would find it showing this:
|
|
Most of that is fine except for the ugly undefined
. Ugh! If we were to return this back to the sheet we would get the undefined
word populating our sheet.
So what can we do?
There are a couple of things, but one such simple way is to apply the ||
conditional on that final map
method, making it look like this:
|
|
Now the result is looking much neater and we can return the results as is back to the sheet.
Anyway, be mindful of undefined
when working with arrays and objects when sucking data out from Google Spreadsheets playing with it and then returning it back to the sheet. It could make for an unsightly sheet!