[英]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
. 我想使用lodash
get
来访问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: 您需要将
key
的值放入路径字符串中:
_.get(test, key + '.bar');
In ES2015 you can use a template literal (interpolated string): 在ES2015中,您可以使用模板文字 (插值字符串):
_.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>)
在获取
JSON.parse(<YOUR JSON String or Obj>)
之前解析JSON
const test = { foo: { bar: 23 } };
const key = 'foo';
const result = _get(JSON.parse(test), key );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.