google sheets | get google sheet info | get worksheet rows | Search

The getDataSheet function retrieves data from a specified worksheet in a Google Sheet and converts it into a structured array of objects. This function is designed to be used by other parts of an application to easily access and work with Google Sheet data.

Run example

npm run import -- "get google data sheet"

get google data sheet

var importer = require('../Core');
var getRows = importer.import("get worksheet rows");

var rowsToObjects = (rows, columns) =>
    rows.reduce((acc, o, i) =>
                (acc[i] = o.reduce((obj, cell, j) =>
                                   (obj[columns[j]] = cell, obj), {}), acc), [])

function getDataSheet(link, worksheet) {
    return getRows(link, worksheet).then(rows => rowsToObjects(rows.slice(1), rows[0]))
}

module.exports = getDataSheet;

What the code could have been:

// Import the required module and function
const getRows = require('../Core').import('get worksheet rows');

/**
 * Transforms a 2D array into a 1D array of objects.
 * 
 * @param {Array} rows - The 2D array to transform.
 * @param {Array} columns - The header row containing column names.
 * @returns {Array} An array of objects, where each object represents a row.
 */
function rowsToObjects(rows, columns) {
    // Check if the input rows and columns are valid arrays
    if (!Array.isArray(rows) ||!Array.isArray(columns)) {
        throw new Error('Invalid input: rows and columns must be arrays');
    }

    // Use Array.prototype.map to create a new array of objects
    return rows.slice(1).map((row, index) => {
        // Check if the row has the same length as the header row
        if (row.length!== columns.length) {
            throw new Error(`Invalid row at index ${index}: length does not match header row`);
        }

        // Use Object.fromEntries to create a new object with column names as keys
        return Object.fromEntries(row.map((cell, columnIndex) => [columns[columnIndex], cell]));
    });
}

/**
 * Retrieves a data sheet from a Google Sheets link and worksheet name.
 * 
 * @param {String} link - The link to the Google Sheets document.
 * @param {String} worksheet - The name of the worksheet to retrieve.
 * @returns {Promise} A promise resolving to an array of objects, where each object represents a row.
 */
async function getDataSheet(link, worksheet) {
    // Use a try-catch block to handle errors when retrieving the rows
    try {
        // Call the getRows function to retrieve the rows
        const rows = await getRows(link, worksheet);
        
        // Check if the rows are valid
        if (!rows || rows.length === 0) {
            throw new Error('Failed to retrieve rows');
        }

        // Call the rowsToObjects function to transform the rows into objects
        return rowsToObjects(rows, rows[0]);
    } catch (error) {
        // Log the error and rethrow it
        console.error('Error retrieving data sheet:', error);
        throw error;
    }
}

// Export the getDataSheet function
module.exports = getDataSheet;

This code defines a function getDataSheet that fetches and processes data from a specific worksheet in a Google Sheet.

Here's a breakdown:

  1. Dependencies:

  2. rowsToObjects Function:

  3. getDataSheet Function:

  4. Export: The getDataSheet function is exported, allowing other parts of the application to use it to retrieve and structure data from Google Sheets.

Let me know if you'd like a deeper dive into any specific part of the code!