我有一个脚本可插入Google Analytics(分析)自定义维度。这对于我要将自定义维度复制到的新GA属性非常有用。如果目标属性中存在现有的自定义尺寸,则会添加该尺寸。
因此,我要使用
Analytics.Management.CustomDimensions.update()
function updateCustomDims() {
var sourceProperty = 'UA-XXXXXXXX-1'
var sourceAccount = 'XXXXXXXX'
var sourceDimensions = Analytics.Management.CustomDimensions.list(sourceAccount, sourceProperty)
var sourceItems = sourceDimensions['items']
var destinationProperty = 'UA-XXXXXXXX-1'
var destinationAccount = 'XXXXXXXX'
var destinationDimensions = Analytics.Management.CustomDimensions.list(destinationAccount, destinationProperty)
var destinationItems = destinationDimensions['items']
for (var i = 0; i < sourceItems.length; i++) {
var sourceContent = {
'name': sourceItems[i]['name'],
'scope': sourceItems[i]['scope'],
'active': sourceItems[i]['active']
}
for (var i = 0; i < destinationItems.length; i++) {
var destinationContent = {
'name': destinationItems[i]['name'],
'scope': destinationItems[i]['scope'],
'active': destinationItems[i]['active']
}
var cdId = {'id': destinationItems[i]['id']}
if (destinationContent[i] != undefined) {
Analytics.Management.CustomDimensions.update(sourceContent, destinationAccount, destinationProperty, cdId)
} else {
Analytics.Management.CustomDimensions.insert(sourceContent, destinationAccount, destinationProperty)
}
Utilities.sleep(1000)
}
}
}
即使存在现有的自定义尺寸,它也只会追加。它应该更新现有的尺寸。
答案 0 :(得分:0)
可能的问题是您正在访问带有整数键而不是键名称的对象:destinationContent[i]
变为destinationContent[0]
,destinationContent[1]
等。但是您显然已经定义了destinationContent
仅具有键name
,scope
和active
。您还会重复使用迭代器变量i
,这肯定会使脚本以极其混乱的方式表现。
请注意,正确的API参考链接是this one和基础REST API资源here。
假设您要检查目标中是否已存在特定的源尺寸,如果有,请对其进行更新(与插入相比),您将需要执行以下操作:
// Create an associative map between the name of a custom dimension
// and its ID (rather than search an array repeatedly).
const existingDims = destinationItems.reduce(function (acc, item) {
var name = item.name;
acc[name] = item.id;
return acc;
}, {});
sourceItems.forEach(function (sourceItem) {
// Construct the resource for this source item.
var name = sourceItem.name;
var sourceContent = {
name: name,
scope: sourceItem['scope'],
active: sourceItem['active']
};
// Does this resource exist already?
var existingId = existingDims[name];
if (existingId)
// update
else
// insert
});
参考