我正在嘗試對下面“結果”中的物件執行 forEach,通過“類別”和“開始日期”在“sumActual”表中查找單元格值,然后將兩個值相加并將新的總和值設定回“sumActual”中的單元格。
例如,在示例表中,我希望在下面的示例表中包含以下內容。
B3: 100 (90 10)
C3:100 (80 20)
B4:1600(1500 100)
C4:266 (66 200)
我只是不知道如何通過“類別”和“開始日期”感興趣的地方找到單元格值。
在此先感謝您的支持。
{ result:
[ { category: 'Credit Card Fees',
month: 'January',
year: 2021,
amount: 90,
startofMonth: '01/01/2021' },
{ category: 'Credit Card Fees',
month: 'February',
year: 2021,
amount: 80,
startofMonth: '02/01/2021' },
{ category: 'Processing',
month: 'January',
year: 2021,
amount: 1500,
startofMonth: '01/01/2021' },
{ category: 'Processing',
month: 'February',
year: 2021,
amount: 66,
startofMonth: '02/01/2021' } ] }
樣品表

截圖后

uj5u.com熱心網友回復:
我相信你的目標如下。
- 使用問題中的值,您想使用 Google Apps 腳本將上圖轉換為下圖。
在這種情況下,以下示例腳本如何?
示例腳本:
function myFunction() {
// This value is from your question.
const { result } = {
result:
[{
category: 'Credit Card Fees',
month: 'January',
year: 2021,
amount: 90,
startofMonth: '01/01/2021'
},
{
category: 'Credit Card Fees',
month: 'February',
year: 2021,
amount: 80,
startofMonth: '02/01/2021'
},
{
category: 'Processing',
month: 'January',
year: 2021,
amount: 1500,
startofMonth: '01/01/2021'
},
{
category: 'Processing',
month: 'February',
year: 2021,
amount: 66,
startofMonth: '02/01/2021'
}]
};
const obj = result.reduce((o, { category, amount, startofMonth }) => (o[startofMonth category] = amount, o), {});
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sumActual");
const [[, ...header], , ...values] = sheet.getDataRange().getValues();
const res = values.map(([h, ...v]) => v.map((f, j) => {
const key = Utilities.formatDate(header[j], Session.getScriptTimeZone(), "MM/dd/yyyy") h;
return obj[key] ? obj[key] f : f;
}));
sheet.getRange(3, 2, res.length, res[0].length).setValues(res);
}
- 運行此腳本時,將使用問題中的值更新作業表“sumActual”的單元格。您問題中底部影像中的目標可以從上部影像中實作。
筆記:
- 此示例腳本適用于您的示例影像。所以當你的實際情況與它不同時,這個腳本可能無法使用。請注意這一點。
參考:
- 減少()
- 地圖()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389692.html
