标题映射功能

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年6月26日 18:29:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定