Created
October 23, 2019 10:34
-
-
Save postman31/ebe25f885bdf42e962d00ecca03f9170 to your computer and use it in GitHub Desktop.
Aggregation function for Ads Script Reports
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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