英文:
Header Mapping Function
问题
以下是您期望的标题:
campaign_id,campaign_source,campaign_medium,campaign_name,date_column,cost_column,clicks_column,impressions_column
英文:
I am trying to write an app script function that rewrite the header based on the mapping.
Below my code:
function headerMapping() {
// var values = sheet.getDataRange().getValues();
// var originalHeaders = values[0];
var values = [['Campaign Id', 'Source', 'Medium', 'Campaign', 'Date', 'Spend', 'Clicks', 'Impressions'], ['563573', 'bing', 'cpc', 'Search', 'Sun Jun 25 00:00:00 GMT+01:00 2023', '18.97', '7.0', '11.0']];
var originalHeaders = ['Campaign Id', 'Source', 'Medium', 'Campaign', 'Date', 'Spend', 'Clicks', 'Impressions'];
var headerMapping = {
'Campaign Id': 'campaign_id',
'Source': 'campaign_source',
'Medium': 'campaign_medium',
'Campaign': 'campaign_name',
'Date': 'date_column',
'Cost': 'cost_column',
'Clicks': 'clicks_column',
'Impressions': 'impressions_column'
};
// Rewrite the headers based on the mapping
var newHeaders = originalHeaders.map(function(header) {
return headerMapping[header.toLowerCase()] || header;
});
// Create the CSV data with the new headers
var csvData = [newHeaders.join(',')];
for (var i = 1; i < values.length; i++) {
var row = values[i];
var formattedRow = [];
for (var j = 0; j < row.length; j++) {
var value = row[j];
// Format date column as YYYY-MM-DD
if (originalHeaders[j].toLowerCase() === 'date' && value instanceof Date) {
value = Utilities.formatDate(value, spreadsheet.getSpreadsheetTimeZone(), 'YYYY-MM-dd');
}
formattedRow.push(value);
}
csvData.push(formattedRow.join(','));
}
Logger.log(csvData.join('\n'));
}
This code return this header:
>Campaign Id,Source,Medium,Campaign,date_column,Spend,Clicks,Impressions
I expect this header:
>campaign_id,campaign_source,campaign_medium,campaign_name,date_column,cost_column,clicks_column,impressions_column
Any help?
答案1
得分: 0
return headerMapping[header.toLowerCase()] || header;
只会匹配小写的标头。请改用
return headerMapping[header] || header;
代替。
英文:
return headerMapping[header.toLowerCase()] || header;
will only match lowercase headers. Use
return headerMapping[header] || header;
instead.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论