我有以下内容
const key = 'foo';
const test = { foo: { bar: 23 } };
Run Code Online (Sandbox Code Playgroud)
我想用lodash get来访问它的值test[key].bar.
我想在第一个指标上使用括号表示法......
_.get(test, '[key].bar'); // results in undefined
Run Code Online (Sandbox Code Playgroud)
当然有办法......
Tim*_*imo 16
您可以传递数组以定义评估路径.
这是一个非常干净的解决方案:
const test = {foo: {bar: 23}}
const key = 'foo'
console.log(_.get(test, [key, 'bar'])) // 23Run Code Online (Sandbox Code Playgroud)
<script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script>Run Code Online (Sandbox Code Playgroud)
joe*_*ews 14
你需要把该值的key到你的路径字符串:
_.get(test, key + '.bar');
Run Code Online (Sandbox Code Playgroud)
在ES2015中,您可以使用模板文字(插值字符串):
_.get(test, `${key}.bar`);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15794 次 |
| 最近记录: |