sfletche sfletche - 5 months ago 38
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
to access the value of

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

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

Surely there's a way...


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