sfletche sfletche - 1 year ago 126
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...

Answer Source

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`);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download