Skip to content

Instantly share code, notes, and snippets.

@postman31
Created October 23, 2019 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postman31/ebe25f885bdf42e962d00ecca03f9170 to your computer and use it in GitHub Desktop.
Save postman31/ebe25f885bdf42e962d00ecca03f9170 to your computer and use it in GitHub Desktop.
Aggregation function for Ads Script Reports
function report2Set(query, idKey, optArgs) {
var reg = /SELECT\s+(.+)\s+FROM.*/
var list = query.match(reg)
if (!list && !list[1]) throw 'Error parsing parameters from %q'.replace('%q', query)
list = list[1].replace(/\s+/, '').split(',')
if (list.length < 1) throw 'Error parsing parameters from %q'.replace('%q', query)
if (typeof idKey == 'string') {
if (!idKey.match(/id/i)) throw 'Bad idKey argument %id'.replace('%id', idKey)
if (list.indexOf(idKey) == -1) throw '%id not founf in %q parameters'.replace('%q', query).replace('%id', idKey)
}
var report = AdsApp.report(query, optArgs), aggregation = null
var rows = report.rows()
if (rows.hasNext()) { aggregation = {} } else { return null }
while (rows.hasNext()) {
var row = rows.next()
var id = (typeof idKey != 'function') ? row[idKey] : idKey(row)
// debug ('typeof idKey "%s"', typeof idKey)
var wrap = list.reduce(function(agg, key) { agg[key] = row[key]; return agg }, {})
if (aggregation[id] && !aggregation[id].push) aggregation[id] = [aggregation[id]]
if (aggregation[id] && aggregation[id].push) {
aggregation[id].push(wrap)
} else {
aggregation[id] = wrap
}
}
return aggregation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment