繁体   English   中英

使用Lodash`_.get`使用括号表示法访问对象键

[英]Using Lodash `_.get` to access object key using bracket notation

我有以下内容

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

我想使用lodash get来访问test[key].bar的值。

我想在第一个指标上使用括号表示法......

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

当然有办法......

您需要将key放入路径字符串中:

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

在ES2015中,您可以使用模板文字 (插值字符串):

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

您可以传递数组以定义评估路径。

这是一个非常干净的解决方案:

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

这是一个使用全局变量的提案,当括在括号中时。

 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]')); 

在获取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.

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