sfletche sfletche - 29 days ago 8
Javascript Question

Using Lodash `_.get` to access object key using bracket notation

I have the following

const key = 'foo';
const test = { foo: { bar: 23 } };


and I'd like to use lodash
get
to access the value of
test[key].bar
.

I want to use the bracket notation on the first indicator...

_.get(test, '[key].bar'); // results in undefined


Surely there's a way...

Answer

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`);