Reputation: 1
I have a script to insert Google Analytics custom dimensions. This is useful for new GA properties i want to copy custom dimensions over to. It will append if there are existing custom dimensions in the destination properties.
Therefore, i want to use
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)
}
}
}
It will only append even though there are existing custom dimensions. It should update the existing dimension.
Upvotes: 0
Views: 538
Reputation: 9862
Probably your issue is that you are accessing an object with an integer key and not the name of the key: destinationContent[i]
becomes destinationContent[0]
, destinationContent[1]
, etc. Yet you clearly have defined destinationContent
to have only the keys name
, scope
, and active
. You also have a double-use of the iterator variable i
, which is certainly going to make your script behave in exceedingly confusing manners.
Note that a proper API reference link is this one with the underlying REST API resource here.
Assuming you want to check if a particular source dimension already exists in the destination, and if so, update it (vs. inserting it), you would want to do something like:
// 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
});
Refs
Upvotes: 1