Google apps 脚本 - 使用对象中的值进行计算

问题描述 投票:0回答:2

我使用 Apps 脚本将 Google Sheets 数据库转换为对象数组。 该对象由 4 个值组成。 {id:1,value_1:1,value_2:2,value_3:3}。

enter image description here

这就是代码:

function getDatabaseAsObjectArray() {

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('database');
  const values = sheet.getDataRange().getValues();
  const headers = values[0];
  const databaseAsObjectArray = [];

  for (let i = 1; i < values.length; i++) {
    const entry = {};
    for (let j = 0; j < headers.length; j++) {
      const key = headers[j];
      if (key === '') continue;
      entry[key] = values[i][j];
    }
    databaseAsObjectArray.push(entry);
  }
  
}

现在,我正在寻找一种解决方案来计算第五个值(来自 value_2 和 value_3),该值在计算后添加到对象数组中:

要执行的步骤: 对象数组 --> {id: 1, value_1: 1, value_2: 2, value_3: 3}

计算新值:value_4 = value_2 + value_3

将 value_4 附加到对象数组:{id: 1, value_1: 1, value_2: 2, value_3: 3, value_4: 5}

有人有办法解决我的问题吗?我不熟悉使用对象...

干杯

arrays object google-apps-script google-sheets
2个回答
0
投票

在for循环后简单添加加法,如下所示:

function getDatabaseAsObjectArray() {

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('Sheet1');
  const values = sheet.getDataRange().getValues();
  const headers = values[0];
  const databaseAsObjectArray = [];

  for (let i = 1; i < values.length; i++) {
    const entry = {};
    for (let j = 0; j < headers.length; j++) {
      const key = headers[j];
      if (key === '') continue;
      entry[key] = values[i][j];
    }
    entry.value_4 = entry.value_2+entry.value_3;
    databaseAsObjectArray.push(entry);
  }
}

0
投票

@TheWizEd,感谢您的帖子。我找到了类似的解决方案。

function getDatabaseAsObjectArray() {

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('Sheet1');
  const values = sheet.getDataRange().getValues();
  const headers = values[0];
  const databaseAsObjectArray = [];

  for (let i = 1; i < values.length; i++) {
    const entry = {};
    for (let j = 0; j < headers.length; j++) {
      const key = headers[j];
      if (key === '') continue;
      entry[key] = values[i][j];
    }

    entry['value_4'] = entry['value_2'] + entry.´['value_3'] * 5 / 100;
    
    databaseAsObjectArray.push(entry);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.