先感謝您!
目標/幫助請求:
我想使用我的代碼中的陣列(我認為它是一個物件文字?),如果資料集(食物列)發生完全匹配,它將陣列中的配對答案插入到“配對“ 柱子。
問題/想法:
我想我需要使用 Object.values()& Object.keys()。我很難讓我的函式通過資料運行并進行比較....我認為 for 陳述句可以作業,但似乎不是這樣,我的 forEach 代碼說它不是一個函式,我是有點迷失如何讓它像使用 i 一樣遍歷每個相應的行。
腳本前的作業表:

期望的輸出:

資料:
| 食物 | 配對 | 成本 |
|---|---|---|
| 蘋果吐司 | ||
| 蘋果奶酪 | ||
| 橘子 | ||
| 橘皮 | ||
| 蘋果 蘋果 蘋果 | ||
| 橙橙 | ||
| 橘子吐司 |
代碼:
function apples() {
sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
const combo = {
'apple toast':'juice',
'apple cheese':'water',
'orange':'milk',
'orange peel':'OJ'
}
const food = sheet.getRange("A2:A5").getValues().flat();
const foodrownum = sheet.getDataRange().getNumRows();
const pairing = sheet.getRange("B2:B5");
var keys = Object.keys(combo)
combo.forEach(function(item,index,array){
if(item===food){
sheet.getRange(2,2,foodrownum).setValue(Object.values(combo));
}
});
}//end of function
參考:
- 如何訪問 javascript 物件文字的各個元素?
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#object_literals
uj5u.com熱心網友回復:
修改點:
- 在
setValue回圈中使用時,處理成本變高。參考 combo是 JSON 物件。在這種情況下,您不能直接使用forEach.- 在 的情況下
sheet.getRange(2,2,foodrownum).setValue(Object.values(combo)),當使用您的值時combo,只會juice將其放入“B”列。 - 我認為在您的情況下,使用 JSON 物件從“A”列的值創建輸出值的方法
combo可能是合適的。
當這些點反映到示例腳本中時,它變成如下。
示例腳本:
function apples() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
const combo = {
'apple toast': 'juice',
'apple cheese': 'water',
'orange': 'milk',
'orange peel': 'OJ'
};
const range = sheet.getRange("A2:A" sheet.getLastRow());
const values = range.getValues().map(([a]) => [combo[a.trim()] || null]);
range.offset(0, 1).setValues(values);
}
- 當此腳本運行時,使用
combo“A”列的值,新值將被放入“B”列。
參考:
- 地圖()
- 獲取值()
- 設定值(值)
uj5u.com熱心網友回復:
你可以試試這個:
function apples() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
const combo = {
'apple toast': 'juice',
'apple cheese': 'water',
'orange': 'milk',
'orange peel': 'OJ'
}
const food = sheet.getRange("A2:A8").getValues().flat();
const pairing = sheet.getRange("B2:B8");
const entries = Object.entries(combo);
for (let i = 0; i < food.length; i ) {
if (food[i] in combo) {
pairing.getCell(i 1, 1).setValue(combo[food[i]]) //Adds the value to each row depending on the key value
}
else {
pairing.getCell(i 1, 1).setValue('Not found')
/*This since both combo and your sheet elements are not the same size
and getCell specifies where we want to insert the value of the key found*/
}
}
}
至于為什么你會得到這個錯誤,基本上它的實作方式根據檔案是不正確的
- 獲取細胞()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452730.html
標籤:谷歌应用脚本
