简体   繁体   中英

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

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

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> 

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

const result = _get(test, search);

This is a proposal which uses a global variable, when 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]')); 

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

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


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM