Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 822
sfletche Avatar asked Nov 10 '16 19:11

sfletche


People also ask

How do I get the object key in Lodash?

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.

What does get from Lodash do?

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.

What is bracket notation in JavaScript?

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.


1 Answers

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>
like image 147
TimoStaudinger Avatar answered Sep 18 '22 15:09

TimoStaudinger