As you delve deeper into Google Apps Script, you'll find yourself working with data more extensively. Efficiently handling and manipulating this data is crucial for building robust and performant scripts. This section explores advanced techniques using JavaScript arrays and objects, the fundamental building blocks for structured data in Apps Script.
Arrays are ordered lists of values. They are incredibly versatile for storing collections of similar data, like rows from a spreadsheet or a list of email subjects. Understanding how to access, modify, and iterate through arrays is a cornerstone of effective scripting.
let fruits = ['Apple', 'Banana', 'Orange'];
// Accessing elements by index (starting from 0)
console.log(fruits[0]); // Output: Apple
console.log(fruits[1]); // Output: Banana
// Adding an element to the end
fruits.push('Grape');
console.log(fruits); // Output: [ 'Apple', 'Banana', 'Orange', 'Grape' ]
// Removing the last element
fruits.pop();
console.log(fruits); // Output: [ 'Apple', 'Banana', 'Orange' ]
// Getting the number of elements
console.log(fruits.length); // Output: 3Iterating through arrays is a common task. The for loop is a classic approach, but for more modern and often cleaner code, you can leverage methods like forEach, map, and filter.
// Using forEach to loop and perform an action
fruits.forEach(function(fruit, index) {
console.log('Fruit at index ' + index + ': ' + fruit);
});
// Using map to transform each element into a new array
let uppercasedFruits = fruits.map(function(fruit) {
return fruit.toUpperCase();
});
console.log(uppercasedFruits); // Output: [ 'APPLE', 'BANANA', 'ORANGE' ]
// Using filter to create a new array with elements that meet a condition
let shortFruits = fruits.filter(function(fruit) {
return fruit.length < 6;
});
console.log(shortFruits); // Output: [ 'Apple' ]Objects, on the other hand, are collections of key-value pairs. They are ideal for representing structured data with named properties, much like a record or a row in a database where each column has a name.
let student = {
name: 'Alice',
age: 20,
major: 'Computer Science',
isEnrolled: true,
courses: ['Math', 'Physics', 'Programming']
};
// Accessing properties using dot notation
console.log(student.name); // Output: Alice
console.log(student.age); // Output: 20
// Accessing properties using bracket notation (useful for dynamic keys)
console.log(student['major']); // Output: Computer Science
let propertyName = 'isEnrolled';
console.log(student[propertyName]); // Output: true
// Adding a new property
student.gpa = 3.8;
console.log(student.gpa); // Output: 3.8
// Modifying an existing property
student.age = 21;
console.log(student.age); // Output: 21