1

I'm trying to create a javascript object that contains nested properties where some of the property names need to be generated dynamically. The following is what I have that is already working:

postObject[campaignObj.campaignName] = {
    "campaignSet" : {
      "groupName" : groupObj.adGroupName,
      "textads" : groupObj.textAds
    }
}

However, I need "campaignSet" to be named dynamically from a variable or other object value. The possibility exists for several campaign sets to exist that must all be contained under postObject[campaignObj.campaignName].

My thought process was that something like the options below should work

postObject[campaignObj.campaignName] = {
    [campaignObj.campaignSet] : {
      "groupName" : groupObj.adGroupName,
      "textads" : groupObj.textAds
    }
}

but this code above keeps throwing an "Invalid property ID" error.

So I tried this

postObject[campaignObj.campaignName] = {
    campaignObj.campaignSet : {
      "groupName" : groupObj.adGroupName,
      "textads" : groupObj.textAds
    }
}

Which caused "Missing : after property ID".

I feel this should be pretty straightforward but it continues to elude me. Any help would be greatly appreciated.

Jonathan
  • 323
  • 2
  • 11
  • Actually, your first thought is valid ES6 :-) – Bergi Aug 11 '15 at 19:36
  • Thanks Bergi, at least I know I'm not completely crazy lol. – Jonathan Aug 11 '15 at 19:38
  • Unfortunately, this javascript snippet is for Google Adwords Scripts which doesn't support ES6 just yet. Daniel's answer below works for Adwords Scripts which supports up to ES5 currently. – Jonathan Aug 11 '15 at 19:44

1 Answers1

2

This should do it:

postObject[campaignObj.campaignName] = postObject[campaignObj.campaignName] || {}; // in case is not defined

postObject[campaignObj.campaignName][campaignSetDynamicName] = {
  "groupName" : groupObj.adGroupName,
  "textads" : groupObj.textAds
} 
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44