javascriptjsongoogle-dfpgoogle-publisher-tag

Set DFP targeting key-values stored in JSON object


I am attempting to store a list of DFP key-values in a JSON object and use javascript to loop each key-value pair in the list to set them as page-level targeting parameters in Google Publisher Tags.

window.dfpData = {"dfpKV":{"key1":"value","key2":"value2","key3":"value1,value2,value3","key4":["value4","value5","value6"]}}

I'm using this function, which doesn't throw any errors but also doesn't appear to execute:

  if (dfpData.dfpKV) {
for (var i = 0; i < dfpData.dfpKV; i ++) {
  var item = dfpData.dfpKV[i];
  googletag.pubads().setTargeting(item[0], item[1]);
}

The resulting output should be the equivalent of multiple lines of:

googletag.pubads().setTargeting("key1",["value"]);
googletag.pubads().setTargeting("key2",["value2"]);
googletag.pubads().setTargeting("key3",["value1,value2,value3"]);
googletag.pubads().setTargeting("key4",["value4","value5","value6"]);

Codepen is here:

Any help you can offer would be much appreciated!


Solution

  • This not the correct way to loop through the values contained within an object. Try

    if (dfpData.dfpKV) {
      Object.keys(dfpData.dfpKV).forEach(function(key) {
         googletag.pubads().setTargeting(key, dfpData.dfpKV[key]);
      })
    }