ユーザ用ツール

サイト用ツール


gas:example:mutablelist

mutable(可変長)リストを作成し、各要素の要素名で参照する

一つ上へ

function createMutableListWithData() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
 
  // ヘッダー行のデータを取得
  const headerRow = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
 
  // 空白でないカラム名のインデックスを取得
  const nonEmptyHeaders = [];
  headerRow.forEach((columnName, columnIndex) => {
    if (columnName !== "") {
      nonEmptyHeaders.push(columnIndex);
    }
  });
 
  // 2行目以降のデータを取得し、カラム名との mutableList を作成
  const dataRows = sheet.getRange(2, 1, sheet.getLastRow() - 1, sheet.getLastColumn()).getValues();
  const mutableList = [];
  dataRows.forEach(dataRow => {
    const rowData = {};
    nonEmptyHeaders.forEach(headerIndex => {
      const columnName = headerRow[headerIndex];
      rowData[columnName] = dataRow[headerIndex];
    });
    mutableList.push(rowData);
  });
 
  // mutableList の内容をログに表示
  Logger.log(mutableList);
 
  // mutableList の各要素をカラム名で参照して表示
  mutableList.forEach(rowData => {
    Object.keys(rowData).forEach(columnName => {
      const value = rowData[columnName];
      Logger.log("Column: " + columnName + ", Value: " + value);
    });
  });
}

例えば、特定の要素を参照したければvalue2 = rowData[“column2”];のようにする。

gas/example/mutablelist.txt · 最終更新: 2023/08/07 12:49 by mikoto