Nested object properties with dynamic name
<p>Context: I'm writing a Redux reducer (although this question is not Redux-specific) for my app's settings, which is a nested object. I want to modify the settings object using property names that are given dynamically.</p>

<p>Example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const settings = {
  service: {
    username: 'TEST',
    password: ''
  }
}

// Normally this would be passed by Redux, but for the purposes of this exercise it's hardcoded

const settingKey = 'service.username';

console.log(settings[settingKey]); // undefined

console.log(eval(`settings.${settingKey}`)); // works, but bad</code></pre>
</div>
</div>
</p>

<p>The only way I can think of accessing the subobject without using eval is using a regex to split the <code>settingKey</code> into its component parts:</p>

<pre><code>const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]];
</code></pre>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const settings = {
  service: {
      username: 'TEST',
      password: ''
  }
}

const settingKey = 'service.username';

const match = /(.+)\.(.+)/.exec(settingKey);

console.log(settings[match[1]][match[2]]);</code></pre>
</div>
</div>
</p>

<p>This works, but</p>

<ol>
<li>It's ugly</li>
<li>It doesn't work for more deeply nested objects</li>
</ol>

<p>Is there a way of accessing a nested object's properties with a dynamic name without using regexes or eval?</p>