Using Lodash `_.get` to access object key using bracket notation
You can pass an array to define the evaluation path.
This is one pretty clean solution to your problem:
const test = {foo: {bar: 23}}
const key = 'foo'
console.log(_.get(test, [key, 'bar'])) // 23
<script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script>
You need to put the value of key
into your path string:
_.get(test, key + '.bar');
In ES2015 you can use a template literal (interpolated string):
_.get(test, `${key}.bar`);