Exploring Objects in Apps Script
This post is a corrected post after AI explains the code included in the book “Google Apps Script 101: Building Work Automation For Free”. Added a strikethrough when editing what AI has written, and added color when edited by author
Summary
In this blog post, we will explore how to work with objects in Apps Script. We will learn how to access object properties using dot notation and square brackets, as well as dynamically accessing properties using variables.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function myObject() { let obj = { key1: 'value1', key2: 'value2', key3: 'value3' } Logger.log(obj.key1) Logger.log(obj['key1']) let keyName = 'key1' Logger.log(obj[keyName]) } |
Code Explanation
The code declares a function named myObject
. Inside the function, an object obj
is created with three key-value pairs.
The Logger.log
statements are used to print the value of the key1
property of the obj
object. The property value can be accessed using both dot notation and square brackets.
A variable keyName
is declared and assigned the value 'key1'
. The value of the keyName
variable is then used to access the key1
property of the obj
object.
Example
When the myObject
function is executed, the following values will be logged in the Apps Script Logger:
1 2 3 |
value1 value1 value1 |
AI Prompt
Write a function that creates an object with three key-value pairs. Log the value of the first key using both dot notation and square brackets. Use a variable to dynamically access the value of the first key.