title: Javascript: how to dynamically create nested objects using object names given by an array
body: <p>I hope someone can help me with this Javascript.</p>
  
  <p>I have an Object called "Settings" and I would like to write a function that adds new settings to that object.</p>
  
  <p>The new setting's name and value are provided as strings. The string giving the setting's name is then split by the underscores into an array. The new setting should get added to the existing "Settings" object by creating new nested objects with the names given by each part of the array, except the last part which should be a string giving the setting's value. I should then be able to refer to the setting and e.g. alert its value. I can do this in a static way like this...</p>
  
  <pre><code>var Settings = {};
  var newSettingName = "Modules_Video_Plugin";
  var newSettingValue = "JWPlayer";
  var newSettingNameArray = newSettingName.split("_");
  
  Settings[newSettingNameArray[0]] = {};
  Settings[newSettingNameArray[0]][newSettingNameArray[1]] = {};
  Settings[newSettingNameArray[0]][newSettingNameArray[1]][newSettingNameArray[2]] = newSettingValue;
  
  alert(Settings.Modules.Mediaplayers.Video.Plugin);
  </code></pre>
  
  <p>... the part that creates the nested objects is doing this ...</p>
  
  <pre><code>Settings["Modules"] = {};
  Settings["Modules"]["Video"] = {};
  Settings["Modules"]["Video"]["Plugin"] = "JWPlayer";
  </code></pre>
  
  <p>However, as the number of parts that make up the setting name can vary, e.g. a newSettingName could be "Modules_Floorplan_Image_Src", I'd like to do this dynamically using a function such as...</p>
  
  <pre><code>createSetting (newSettingNameArray, newSettingValue);
  
  function createSetting(setting, value) {
      // code to create new setting goes here
  }
  </code></pre>
  
  <p>Can anyone help me work out how to do this dynamically?</p>
  
  <p>I presume there has to be a for...loop in there to itterate through the array, but I haven't been able to work out a way to create the nested objects.</p>
  
  <p>If you've got this far thanks very much for taking the time to read even if you can't help.</p>