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: 21Iterating through object properties requires different methods. for...in loop is commonly used, and Object.keys(), Object.values(), and Object.entries() provide more structured ways to work with object properties.
// Using for...in loop to iterate over keys
for (let key in student) {
console.log(key + ': ' + student[key]);
}
// Using Object.keys() to get an array of keys
let keys = Object.keys(student);
console.log(keys); // Output: [ 'name', 'age', 'major', 'isEnrolled', 'courses', 'gpa' ]
// Using Object.values() to get an array of values
let values = Object.values(student);
console.log(values); // Output: [ 'Alice', 21, 'Computer Science', true, [ 'Math', 'Physics', 'Programming' ], 3.8 ]
// Using Object.entries() to get an array of [key, value] pairs
let entries = Object.entries(student);
console.log(entries); // Output: [ [ 'name', 'Alice' ], [ 'age', 21 ], ... ]Combining arrays and objects is where data handling truly shines. You'll often encounter data structures that are arrays of objects, such as the data returned from a Google Sheet or a JSON API. This pattern allows for rich, structured datasets.
let users = [
{ id: 1, name: 'Bob', email: 'bob@example.com' },
{ id: 2, name: 'Charlie', email: 'charlie@example.com' },
{ id: 3, name: 'David', email: 'david@example.com' }
];
// Finding a user by ID
let userIdToFind = 2;
let foundUser = users.find(function(user) {
return user.id === userIdToFind;
});
console.log(foundUser); // Output: { id: 2, name: 'Charlie', email: 'charlie@example.com' }
// Getting all user names
let userNames = users.map(function(user) {
return user.name;
});
console.log(userNames); // Output: [ 'Bob', 'Charlie', 'David' ]
// Filtering users with emails ending in '.com'
let comUsers = users.filter(function(user) {
return user.email.endsWith('.com');
});
console.log(comUsers); // Output: [ { id: 1, name: 'Bob', email: 'bob@example.com' }, ... ]Understanding these array and object manipulation techniques will significantly improve your ability to process and transform data within Google Apps Script. Mastering these concepts lays the groundwork for more complex automations and efficient script development.