Using Lodash `_.get` to access an object key using brackets

I have the following

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

and I would like to use lodash getto access the value test[key].bar.

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

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

Of course there is a way ...

+8
source share
5 answers

You need to put the value keyin the path string:

_.get(test, key + '.bar');

In ES2015, you can use a template literal (interpolated string):

_.get(test, `${key}.bar`);
+14
source

You can pass an array to determine the evaluation path.

This is a 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>
Run code
+12
source
const test = { foo: { bar: 23 } };
const key = 'foo';
const search = key + '.bar';

const result = _get(test, search);
0

This is a sentence that uses a global variable enclosed in brackets.

function getValue(object, path) {
    return path.replace(/(?=\[)/g, '.').split('.').reduce(function (o, k) {
        var m = k.match(/^\[([^\]]*)\]$/);
        return m ? (o || {})[window[m[1]]] : (o || {})[k];
    }, object);
}

var test = { foo: { bar: 23 } },
    key = 'bar';

console.log(getValue(test, 'foo[key]'));
Run code
0
source

Parse JSON before getting JSON.parse(<YOUR JSON String or Obj>)

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


const result = _get(JSON.parse(test), key );
0
source

Source: https://habr.com/ru/post/1660437/


All Articles