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...
The _. keys() method is used to return the list of all keys of the given object. Parameters: This method accepts a single parameter as mentioned above and described below: object: This parameter holds the object elements.
get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.
JavaScript provides a rich collection of tools---including special syntax and operations---that allows us to work with strings. Bracket notation is the special syntax that allows us to access the individual characters that make up a string.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With