Google Apps Script snippets ᕦʕ •ᴥ•ʔᕤ

Simple conversion of an array into a collection

Simple conversion of an array into a collection

Snippet

index.js
/**
 * Converts a 2D array to a collection.
 *
 * @param {Array.<Array.<any>>} array
 * @returns {Array.<object>}
 */
function arrayToCollection_(array) {
  return array.slice(1).map(
    (_, rowIndex) =>
      array[0].reduce((rowCollection, header, columnIndex) => {
        rowCollection[header] = array[rowIndex + 1][columnIndex];
        return rowCollection;
      }, {}),
    []
  );
}

Run it

run.js
/* global arrayToCollection_ arrtocoll_ */

const ARRAY = [
  ['Num', 'Date', 'Name', 'Amount'],
  [1, new Date(), 'Alex', 100],
  [2, new Date(), 'Nate', 200],
  [3, new Date(), 'Piter', 300],
];

/**
 * Runs the snippet
 */
function run() {
  // Don't forget a deep copy
  const array = ARRAY.map((r) => [...r]);
  // Headings become keys
  array[0].forEach((_, i) => (array[0][i] = array[0][i].toLocaleLowerCase()));
  const collection = arrayToCollection_(array);
  console.log(collection);
}

/**
 * Runs the minimized function of the snippet
 */
function runMiniFn() {
  // Don't forget a deep copy
  const array = ARRAY.map((r) => [...r]);
  // Headings become keys
  array[0].forEach((_, i) => (array[0][i] = array[0][i].toLocaleLowerCase()));
  const collection = arrtocoll_(array);
  console.log(collection);
}

Minimized version

For quick use, you can use a more transparent version

index.min.js
function arrtocoll_(e) {
  return e
    .slice(1)
    .map((r, c) => e[0].reduce((r, n, o) => ((r[n] = e[c + 1][o]), r), {}), []);
}

#common